添加 css class 到 tr 失败

Add a css class to tr fails

我正在使用 Bootstrap Table,其中我使用 data-url="data.json" 远程加载数据。所以我的 table:

<table id="mytable" class="table table-hover" data-url="data.json" data-toggle="table" id="table-pagination"  data-pagination="true">
    <thead>
         <tr>
              <th data-field="id" data-align="center">id</th>
              <th data-field="type" data-align="center">type</th>
              <th data-field="name" data-align="center">name</th>
              <th data-field="product" data-align="center">product</th>
              <th data-field="use" data-align="center">use</th>
              <th data-field="quantity" data-sortable="true">quantity</th> 
         </tr>
    </thead>
</table>

最后一列只有数字(没有任何其他字符)。 data.json 是这样的:

[
    {
        "id": 120,
        "type": "type1",
        "name": "name 1",
        "product": "250304-01",
        "use": "use 1",
        "quantity": 10000
    },
    {
        "id": 121,
        "type": "type2",
        "description": "name 2",
        "product": "250124-01",
        "cutter": "use 1",
        "quantity": 80
    }
]

我想检查一下,当最后一列中的值小于 100 时,将在 tr 中添加一个 class。我搜索了一下,发现可以用 filter 来完成。所以,我这样编码:

 $('tbody tr').filter( function(){
                       return $('td:last', this).text() < 100;
                     }).addClass('warning');

我将上面的内容原样保存到一个文件 addWarning.js 中,然后将它放在我页面的底部,在所有其他文件的末尾 scripts

 <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
 <script src="assets/js/bootstrap.min.js"></script>
 <script src="assets/js/bootstrap-table.js"></script>
 <script src="assets/js/bootstrap-table-el-GR.js"></script>
 <script src="assets/js/addWarning.js"></script>

但它不起作用..我错过了什么?

仅在加载远程内容后过滤 table 行,否则 $('tbody tr') 将不会 select 任何元素。因此,您可以为 load-success.bs.table 事件绑定事件处理程序,它会在成功加载远程数据时触发。

$('table').on('load-success.bs.table', function() {
  $('tbody tr').filter(function() {
    return $('td:last', this).text() < 100;
  }).addClass('warning');
});

I save the above as it is to a file addWarning.js and I put it at the bottom of my page in the end of all the other scripts.

这意味着脚本在被点击时运行 - 这是在页面加载过程中。此时 bootstrap table 还没有加载数据,所以过滤器不匹配。

根据文档页面:http://bootstrap-table.wenzhixin.net.cn/documentation/ 您需要监听 load-success.bs.table,您应该能够直接用类似以下内容替换现有代码:

$(function() {
    $(body).on("load-success.bs.table", function() {
        $('tbody tr').filter( function(){
                   return $('td:last', this).text() < 100;
                 }).addClass('warning');
    }); 
});
var tr = $('#mytable tbody tr')

tr.each(function () {
    var td = $(this).find('td:last');
    alert(td.text());
    if (td.text() < 100) {
        td.addClass('warning')
    }


})

这样试试

DEMO

为什么不使用 rowStyle 选项,data-row-style="rowStyle",然后:

function rowStyle(row) {
    if (row.quantity < 100) {
        return {
            classes: 'warning'
        };
    }
    return {};
}

文档:http://bootstrap-table.wenzhixin.net.cn/documentation/#table-options

演示:http://jsfiddle.net/wenyi/e3nk137y/3270/