将 <tr> 的 <td> 值与 JQuery 的依赖关系添加到 <tr>

addClass to <tr> depence of <td> value with JQuery

Bootstrap 提供 .danger class。如果最后一个 <td> 的值大于或等于 0,我想添加这个 class。

我的 Table 看起来与这个相似:

<table>
 <thead>
  <tr>
   <th>#</th>
   <th>Timestamp</th>
   <th>Failures</th>
  </tr>
 </thead>
 <tbody>
  <tr>  
   <th>1</th>
   <td>date</td>
   <td>0</td>
  </tr>
  <tr>  
   <th>2</th>
   <td>date</td>
   <td>2</td>
  </tr>
</tbody>

我尝试了什么:

$(document).ready(function () {
$("table tbody tr").each(function () {
    var cell = $(this).find("td:last-child").text();

   if ($(this).val()>='0') tr.addClass('danger');       
    else tr.removeClass('danger');
    }
});
})

我认为问题在于从 <td> 获取值。或者 jQuery 期望永久写入 <td> 的 class 并从 class 更改为另一个。

变化

  1. 您需要使用当前元素,即 this 代替 tr
  2. 使用 .text() 获取文本,因为 TD 元素没有 value 属性
  3. 为了进行数值比较,将文本转换为合适的日期类型。在示例中,我使用了 parseInt().

代码

$("table tbody tr").each(function() {

   //Read text then it to number
   var cell = parseInt($(this).find("td:last").text(), 10);
   if (cell > 0) {
       $(this).addClass('danger'); //use current element
   } else {
       $(this).removeClass('danger'); //use current element
   }

});

$(document).ready(function() {
  $("table tbody tr").each(function() {

    //Parse text to number
    var cell = parseInt($(this).find("td:last").text(), 10);
    if (cell > 0)
      $(this).addClass('danger'); //use context selector this
    else
      $(this).removeClass('danger'); //use context selector this

  });
})
.danger {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Timestamp</th>
      <th>Failures</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>1</th>
      <td>date</td>
      <td>0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>date</td>
      <td>2</td>
    </tr>
  </tbody>

你有两个错误。

  1. 使用 val() 代替文本
  2. tr 未定义。将 $(this) 赋值给 tr

$(document).ready(function () {
$("table tbody tr").each(function () {
    var cell = $(this).find("td:last-child").text();
    var tr = $(this);

   if (parseFloat($(this).text())>=0) //notice, I have used parseFloat to parse the number
      tr.addClass('danger');       
   else tr.removeClass('danger');
});
})

当您使用像 >= 这样的逻辑运算时,不要使用 " " 中的值,因为这些运算仅适用于数字。

if ($(this).val()>=0) tr.addClass('danger');       
    else tr.removeClass('danger');
    }