条件下在tr中添加cssclass

Add css class in tr under condition

我有一个table

<div class="container">
    <div class="row">
      <table id="mytable">
        <thead>
            <tr>
                <th>Item ID</th>
                <th>Item Name</th>
                <th>Item Price</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Item 1</td>
                <td></td>
            </tr>
            <tr>
                <td>2</td>
                <td>Item 2</td>
                <td>0</td>
            </tr>
        </tbody>
      </table>
    </div>
</div>

我想进行检查,如果列项目价格的值低于 100,请在 tr 中添加 class="warning

<tr class="warning">
 <td>1</td>
 <td>Item 1</td>
 <td></td>
</tr>

我如何用 jquery 做到这一点 我对 jquery 了解不多,我的 try 直到现在都不成功。

$('#mytable tr/* how i check here <100*/ ').addClass('warning');

这里可以用filter()

filter() : For each element, if the function returns true (or a "truthy" value), the element will be included in the filtered set; otherwise, it will be excluded. ( Taken from http://api.jquery.com/filter/ )

$('tbody tr').filter(function() {
  return $('td:eq(2)', this)
    // get 3rd column using :eq(), :nth-child , :last or :last-child
    .text()
    // get text content
    .substr(1) * 1 < 100;
  // get number value from string by avoiding $ and compare
  // if it includes , then use txt.replace(/[,$]/g,'')
  // use parseInt(txt,10) for converting to integer
}).addClass('warning');
.warning {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <table id="mytable">
      <thead>
        <tr>
          <th>Item ID</th>
          <th>Item Name</th>
          <th>Item Price</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>Item 1</td>
          <td></td>
        </tr>
        <tr>
          <td>2</td>
          <td>Item 2</td>
          <td>0</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

你最好的选择是编写一些代码,而不是试图找到一些晦涩或自定义的选择器:

$("#mytable tr").each(function() {
    var val = $("td", this)[2].text().substr(1) * 1;
    if (val < 100) 
        $(this).addClass("warning");
});

就个人而言,我会通过添加 class(名称无关紧要)使其比依赖列排序更易于维护:

<tr> 
  <td>1</td>
  <td>Item 1</td>
  <td class='data-value'></td>
</tr>

然后:

$("#mytable tr").each(function() {
    var val = $("td.data-value", this).text().substr(1) * 1;
    if (val < 100) 
        $(this).addClass("warning");
});

编辑: 添加了 .substr(1),因为 .text() 将给出包含“$”的值,然后 *1 将其作为数字获取.您可以改为使用 parse int 并记住将其设置为基数 10。

使用过滤器:

http://api.jquery.com/filter/

您还需要正则表达式从数字中去除货币。

然后抓取最近的TR并应用class。

http://jsfiddle.net/SeanWessell/g6uz2Lfx/

$('#mytable tr td:nth-child(3)').filter(function () {
    var amt = parseFloat($(this).text().replace(/[$,]+/g, ""));
    return (amt < 100);
}).closest('tr').addClass('warning');