![](/img/trans.png)
[英]How to set table cell appearance depending on table cell value in Handsontable
[英]How to apply CSS to table cell depending on conditions
我有一個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。
代碼稍有變化即可使其正常工作
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.