如何根据条件将CSS应用于表格单元格

时间:2016-06-09 10:44:38

标签: javascript html css

我有一个包含10行的表,数据是

ABC XYZ 30% (ABC)
ABC MNO 91% (XYZ)



var table = document.getElementById("table2");
for (var i = 0, row; row = table.rows[i]; i++) {
   for (var j = 0, col; col = row.cells[j]; j++) {
   var data = col.innerText;
   var data1 = data.split(" ");
   if(data1[0] == "91%"){
        row.cells[j].css( "color", "red" );
   }
   }  
}

我想为90%以上的细胞添加红色。怎么做。 我知道在后端我们可以做到但现在我只使用html和CSS。

1 个答案:

答案 0 :(得分:2)

代码中的轻微变化可以使其正常工作

var table = document.getElementById("table2");
for (var i = 0, row; row = table.rows[i]; i++) {
  for (var j = 0, col; col = row.cells[j]; j++) {
    var data = col.innerText;
    // replace % symbol, parse and compare with number
    if (+data.replace('%', '') > 90) {
      // update style property of cell
      col.style.color = "red";
    }
  }
}
<table id="table2">
  <tr>
    <td>ABC</td>
    <td>XYZ</td>
    <td>30%</td>
    <td>(ABC)</td>
  </tr>
  <tr>
    <td>ABC</td>
    <td>MNO</td>
    <td>91%</td>
    <td>(XYZ)</td>
  </tr>
</table>

如果单个列包含整个字符串,则执行类似

的操作

var table = document.getElementById("table2");
for (var i = 0, row; row = table.rows[i]; i++) {
  for (var j = 0, col; col = row.cells[j]; j++) {
    // get the percentage value from string
    var data = col.innerText.match(/(\d+(?:\.\d+)?)%/);
    // check match found or not then parse and compare with number
    if (data && +data[1] > 90) {
      // update style property of cell
      col.style.color = "red";
    }
  }
}
<table id="table2">
  <tr>
    <td>ABC XYZ 30% (ABC)</td>
  </tr>
  <tr>
    <td>ABC MNO 91% (XYZ)</td>
  </tr>
</table>