我有一个表,其中包含一些我想根据它们具有的值来设置颜色的值。我所做的是:
window.onload = setColor();
function setColor() {
var elems = document.getElementsByTagName("td");
for (i = 0; i < elems.length; i++) {
if (elems[i].innerText === "Passed") {
elems[i].style.backgroundColor = "green";
} else if (elems[i].innerText === "Failed") {
elems[i].style.backgroundColor = "red";
}
}
}
<table id="myTable">
<tr>
<th style="width:50%;">SET</th>
<th style="width:50%;">TEST STATUS</th>
</tr>
<tr>
<td>Set</td>
<td>Passed</td>
</tr>
<tr>
<td>Set</td>
<td>Passed</td>
</tr>
</table>
但是正如您所看到的,我正在整体循环td elements
来做到这一点,我认为这不好,是吗?
所以我想到了一些问题:
onload events
设置某种不支持它的elements
,所以我可以执行magicevent=setColor(this)
之类的操作?我希望表格稳定。CSS
中的目标?我不了解CSS
中js
的语法。谢谢你。
我尝试回答您的问题:
td
标签,并在不使用JavaScript的情况下为该类提供CSS规则。 类似:
<style>
.failed{
background-color: red;
}
.passed{
background-color: green;
}
</style>
<table>
<tr><td class="failed">failed </td></tr>
<tr><td class="passed">passed </td></tr>
</table>
当使用elems[i].style.backgroundColor = "red";
时,将background-color
内元素的elems
设置在位置i
。在elems[i]
内部有一个特定的td
。另一种方法是根据测试值(通过或失败)将类添加到td
。但是,我建议以下解决方案:
<table id="myTable">
<tr>
<th style="width:50%;">SET</th>
<th style="width:50%;">TEST STATUS</th>
</tr>
<tr>
<td>Set</td>
<td>Passed</td>
</tr>
<tr>
<td>Set</td>
<td>Passed</td>
</tr>
</table>
<style>
.failed{
background-color: red;
}
.passed{
background-color: green;
}
</style>
<script>
window.onload = setColor();
function setColor(){
var elems = document.getElementsByTagName("td");
for (i = 0; i < elems.length; i++) {
if (elems[i].innerText === "Passed") {
elems[i].classList.add("passed");
}else if (elems[i].innerText === "Failed"){
elems[i].classList.add("failed");
}
}
}
</script>
您的脚本可以更改为以下内容:
function setColor(){
var elems = document.querySelectorAll("#myTable td:last-child");
for (i = 0; i < elems.length; i++) {
if (elems[i].innerText === "Passed") {
elems[i].style.backgroundColor = "green";
}
else if (elems[i].innerText === "Failed")
{
elems[i].style.backgroundColor = "red";
}
}
}
document.addEventListener("DOMContentLoaded", setColor);
<table id="myTable">
<tr>
<th style="width:50%;">SET</th>
<th style="width:50%;">TEST STATUS</th>
</tr>
<tr>
<td>Set</td>
<td>Passed</td>
</tr>
<tr>
<td>Set</td>
<td>Passed</td>
</tr>
</table>
但是最好使用CSS类为文本着色:
if (elems[i].innerText === "Passed") {
elems[i].classList.add("passed");
}
else if (elems[i].innerText === "Failed")
{
elems[i].classList.add("failed");
}
在style.css中:
.passed {
background-color: green;
}
.failed {
background-color: red;
}