Javascript中的HTML表条件格式代码没有按计划工作

HTML Table conditional formatting code in Javascript not working as planned

本文关键字:按计划 工作 代码 格式 中的 HTML 条件 Javascript      更新时间:2023-09-26

我正在尝试创建一组影响行样式的tabletd元素值之间相互依赖的规则。

第一期

我是条件格式我的表行风格不同的背景颜色在某些规则。

预期结果:

  • if Width> 0 => color red
  • if Width == 0 &&> 0 => color blue
  • if Width> 0 &&高度> 0 =>颜色
  • if Width == 0 &&Height == 0 => color white

现实结果

  • Width> 0 => color red ✓Works
  • font =宋体;Height> 0 => color blue ✓Works
  • if Width> 0 &&
  • if Width == 0 &&高度== 0 =>颜色白色✓作品

第二期

是,当我按下选择'每页行'或页码,它失去任何条件样式。

如果您有更好的方法,请随时建议执行此操作的最佳实践。谢谢,这是我的代码:

    <table id="table1"
       data-toggle="table"
       data-url="data1.json"
       data-pagination="true"
       data-sort-order="desc">
    <thead>
    <tr>
        <th data-sortable="true" data-field="name" >Name</th>
        <th data-sortable="true" data-field="W">Width</th>
        <th data-sortable="true" data-field="H">Height</th>
        <th data-sortable="true" data-field="D">Depth</th>
    </tr>
    </thead>
</table>
Javascript

var Counter = null;
$('#table1').on('load-success.bs.table', function () {
        $('td:nth-child(2)').each(function() {
            var redValue = $(this).text();
            if (redValue > 0) {
                var oTableRow = $(this).parent();
                oTableRow.css('background-color', 'red');
                Counter = 1; //W>0
            }else if(redValue == 0){
                Counter = 2;
            }
        });
        $('td:nth-child(3)').each(function() {
            var blueValue = $(this).text();
            var oTableRow = $(this).parent();
            if ((Counter= 2) && (blueValue > 0)) {
                oTableRow.css('background-color', 'blue');
            }else if((Counter == 1)&&(blueValue > 0)){
                oTableRow.css('background-color', 'yellow');
            }
        });
    });
数据集

    [{
  "name": "First Value",
  "W": 0,
  "H": 0,
  "D": 100
},{
"name": "First Value",
"W": 1,
"H": 0,
"D": 100
},{
"name": "First Value",
"W": 0,
"H": 1,
"D": 100
},{
"name": "First Value",
"W": 1,
"H": 1,
"D": 100
}];

正如@charlietfl所说,您希望循环行,然后检查条件并按行设置颜色。然后,我没有使用嵌套的if-else来确定该行的颜色,而是定义了一个2x2表colorMapping,其中包含每个可能结果的颜色:

  • 第一行:height === 0
  • 第二行:height> 0
  • first col: width === 0

这个应该可以完成工作:

$('#table1').on('load-success.bs.table', function(){
    //create a color-mapping
    var colorMapping = [
        'white', 'red',
        'blue',  'yellow'
    ];
    $('tr', this)   //get rows ...
        .has('td')  //... that contain td-nodes
        .each(function(){
            var $row = $(this);
            //get w for this row
            var w = +$row.find('td:eq(1)').text();
            //get h for this row
            var h = +$row.find('td:eq(2)').text();
            //check wich of the four colors to choose
            var color = colorMapping[ (h>0? 2: 0) + (w>0? 1: 0) ];
            //assign color to this row
            $row.css('background-color', color);
        });
});