基于文本的内容,我需要更改颜色,例如:-用于PASS绿色和FAIL红色。这些内容在td标签的表中。我试图写一个js,但无法达到结果。
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
if (document.getElementById("changeColour").innerHTML == "PASS") {
document.getElementById("changeColour").style.color = "#FE2E2E";
}
else if (document.getElementById("changeColour").innerHTML == "FAIL") {
document.getElementById("changeColour").style.backgroundColor = "blue";
</script>
</head>
And my HTML body is is :-
table>
<caption><h4>SUMMARY</h4></caption>
<tr>
<tr>
<td><h6>Operation1</h6></td>
<td id="changeColor">PASS</td>
</tr>
<tr>
<td><h6>Operation2</h6></td>
<td><h6 id="changeColor">FAIL</h6></td>
</tr>
</table>
答案 0 :(得分:0)
两件事,您的脚本甚至在DOM准备就绪之前就在运行,其次id必须是唯一的。在第一种情况下,您可以将脚本放入$(document).ready
内,或将脚本放置在靠近主体标签的地方。
第二个使用通用类并使用document.querySelectorAll
,对其进行迭代,然后检查innerHTML
document.querySelectorAll('.changeColor').forEach(function(item) {
if (item.innerHTML == "PASS") {
item.style.color = "#FE2E2E";
} else if (item.innerHTML == "FAIL") {
item.style.backgroundColor = "blue";
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<caption>
<h4>SUMMARY</h4>
</caption>
<tr>
<tr>
<td>
<h6>Operation1</h6>
</td>
<td class="changeColor">PASS</td>
</tr>
<tr>
<td>
<h6>Operation2</h6>
</td>
<td>
<h6 class="changeColor">FAIL</h6>
</td>
</tr>
</table>
答案 1 :(得分:0)
两个元素的id
值不正确。此外,您可以使用类名称来获取元素并检查PASS
和FAIL
。像这样:
var elem = document.getElementsByClassName('changeColor');
for(var i=0; i<elem.length; i++){
if(elem[i].innerHTML === 'PASS'){
elem[i].style.color = "green";
} else {
elem[i].style.color = "red";
}
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<caption><h4>SUMMARY</h4></caption>
<tr>
<tr>
<td><h6>Operation1</h6></td>
<td class="changeColor">PASS</td>
</tr>
<tr>
<td><h6>Operation2</h6></td>
<td><h6 class="changeColor">FAIL</h6></td>
</tr>
</table>
答案 2 :(得分:0)
您可以使用class来标识多行。因为id必须是唯一的。
var elems = document.getElementsByClassName("changeColor");
for(var i=0; i<elems.length; i++){
if(elems[i].innerText == "PASS"){
elems[i].style.color = "#FE2E2E";
}else{
elems[i].style.color = "blue";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
And my HTML body is is :-
<table>
<caption><h4>SUMMARY</h4></caption>
<tr>
<tr>
<td><h6>Operation1</h6></td>
<td class="changeColor">PASS</td>
</tr>
<tr>
<td><h6>Operation2</h6></td>
<td><h6 class="changeColor">FAIL</h6></td>
</tr>
</table>