【问题标题】:Table column conditional js formatting表格列条件js格式化
【发布时间】:2015-10-23 22:52:19
【问题描述】:

我有一个用 CSS 格式化的 HTML 表格。

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

请指教。

【问题讨论】:

  • 请提供与本题相关的代码块,尤其是表格的HTML代码,如有JS部分代码。

标签: javascript html-table formatting conditional


【解决方案1】:

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

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";
  }
}

【讨论】:

    【解决方案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>

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

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

    【讨论】:

    • 谢谢,但我需要它用于特定列
    • 只需将 id="value" 添加到您需要它的任何列(td 元素)。如果表是动态的,则使用 xpath 插入 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2011-05-20
    相关资源
    最近更新 更多