简体   繁体   English

表格栏条件js格式

[英]Table column conditional js formatting

I have an HTML table formatted with CSS. 我有一个用CSS格式化的HTML表。

I want the cells of the 4th column to have a red background if their value is smaller than -2 and green background if greater than +2. 我希望第4列的单元格的值小于-2时具有红色背景,而大于+2时具有绿色背景。

Please advise. 请指教。

This should get you started.. Change the value in the fourth row to change background colour. 这应该使您入门。.更改第四行中的值以更改背景色。

  (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> 

if the table is dynamic and you want to grab the last element then use xpath. 如果表是动态的,并且您想获取最后一个元素,则使用xpath。

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

The below script will work for your requirement, HERE is a working example for your reference. 下面的脚本将满足您的要求, 此处是一个可供参考的工作示例。 if you have multiple tables just give it a class and amend the script as required. 如果您有多个表,请给它一个类并根据需要修改脚本。

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