Table列条件js格式化

Table column conditional js formatting

我有一个 HTML table 格式为 CSS。

我希望第 4 列 的单元格在值小于 -2 时具有红色背景,在值大于 +2 时具有绿色背景。

请指教

这应该可以帮助您入门。更改第四行中的值以更改背景颜色。

    (function(){
        var valueOfFourthRowValue = document.getElementById("value");
        if (valueOfFourthRowValue.textContent > 2) {
            valueOfFourthRowValue.style.backgroundColor = "green"
        } else if (valueOfFourthRowValue.textContent < -2) {
            valueOfFourthRowValue.style.backgroundColor = "red"
        }

    })()
<table>
    <tr><td>One Row</td></tr>
    <tr><td>One Row</td></tr>
    <tr><td>One Row</td></tr>
    <tr><td id="value">3</td></tr>
</table>

如果 table 是动态的并且您想获取最后一个元素,则使用 xpath。

var tableColumn = document.evaluate('//table//tr[last()]/td', document, null, XPathResult.ANY_TYPE, null).iterateNext();
tableColumn.setAttribute("id", "value");

下面的脚本可以满足您的要求,HERE 是一个工作示例供您参考。 如果您有多个表,只需给它一个 class 并根据需要修改脚本。

var trTags = document.getElementsByTagName("tr");
for (var i = 0; i < trTags.length; i++) {
  var tdFourthEl = trTags[i].children[3]; // starts with 0, so 3 is the 4th element
  if (tdFourthEl.innerText < -2) {
    tdFourthEl.style.backgroundColor = "red";
  } else if (tdFourthEl.innerText > 2) {
    tdFourthEl.style.backgroundColor = "green";
  }
}