提问者:小点点

向表中的列添加类


我想在表的第二列中追加td-value

。输出应为

 <td><div class = 'myclass'>-1.3%</div></td>

我不想使用.addClass(),因为我需要在我的实际问题中追加嵌套的div。我制作了同样的小示例。JsFiddle


共2个答案

匿名用户

我相信这会给你一点思路。

      $(document).ready(function(){
  var CONTROL_INTERVAL2 = setInterval(function(){
  
    $('table tbody td:nth-child(2)').each(function() {
      const value = $(this).text().substr(0,1);
      if ( value == '-') {
        $('table tbody td:nth-child(2)').replaceWith("<div class = 'myclass'>" + $(this).val +"</div>");
      }
      else {
        $(this).css('color', 'green');
      }
      
      clearInterval(CONTROL_INTERVAL2);
    });
    
  }, 2000);
  });

匿名用户

当您使用html(函数)时,这是一个简单的任务

null

$('table tbody td:nth-child(2)').html(function(i,curr){
     return $('<div class="myclass">').text(curr);
})
.myclass{font-weight:900; color:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
  <td>Class1</td>
  <td>-1.3%</td>
  <td>Science</td>
  </tr>
  <tr>
  <td>Class2</td>
  <td>+3.3%</td>
  <td>Maths</td>
  </tr>
 </table>