Javascript中的HTML表条件格式代码无法按计划运行

时间:2016-08-07 21:36:56

标签: javascript jquery html-table

我正在尝试创建一组规则,这些规则在我td table中影响行样式的 <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> 元素值之间相互依赖。

  

第一期

我有条件地格式化我的表行,以根据某些规则设置不同的背景颜色。

预期结果:

  • 如果宽度> 0 =&gt;颜色红色
  • 如果宽度== 0&amp;&amp;高度&gt; 0 =&gt;颜色蓝色
  • 如果宽度> 0&amp;&amp;高度&gt; 0 =&gt;黄色
  • 如果宽度== 0&amp;&amp;高度== 0 =&gt;颜色白色

现实结果

  • 宽度&gt; 0 =&gt;颜色红色✓工作
  • 宽度== 0&amp;&amp;高度&gt; 0 =&gt;颜色为蓝色✓工作
  • 如果宽度> 0&amp;&amp;高度&gt; 0 =&gt;颜色黄色 X不起作用,颜色为蓝色。
  • 如果宽度== 0&amp;&amp;高度== 0 =&gt;颜色白色✓工作
  

第二期

当我按下每页选择&#39;行时#39或者分页编号,它会失去任何条件风格。

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

HTML

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');

            }
        });
    });

的Javascript

    [{
  "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
}];

JSON数据集

com.android.support

1 个答案:

答案 0 :(得分:1)

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

  • 第一行:身高=== 0
  • 第二行:身高&gt; 0
  • first col:width === 0
  • 第二列:宽度&gt; 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);
        });
});