簡體   English   中英

表格欄條件js格式

[英]Table column conditional js formatting

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

我希望第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> 

如果表是動態的,並且您想獲取最后一個元素,則使用xpath。

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

下面的腳本將滿足您的要求, 此處是一個可供參考的工作示例。 如果您有多個表,請給它一個類並根據需要修改腳本。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM