簡體   English   中英

將 class 添加到表中的列

[英]Add class to column in table

我想 append <div class = 'myclass'>td-value</div>在表的第二列。 Output 應該是

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

我不想使用.addclass( )因為我需要在我的實際問題中使用 append 嵌套 div。 我為此制作了一個小例子。 JSFiddle

我相信這會給你一點想法。

      $(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(function)時,這是一個簡單的任務

 $('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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM