2 回答
TA贡献1946条经验 获得超3个赞
以下是当该字段的值为 High 时将文本颜色更改为红色的示例
elements = document.getElementsByTagName("td")
for (var i = elements.length; i--;) {
if (elements[i].innerHTML === "High") {
elements[i].style.color = "red";
}
}
<table id="something">
<tr>
<th>City</th>
<th>Min.</th>
<th>Max.</th>
<th>Delay</th>
</tr>
<tr>
<td>City 1</td>
<td>$20</td>
<td>$23</td>
<td>Medium</td>
</tr>
<tr>
<td>City 2</td>
<td>$20</td>
<td>$23</td>
<td>High</td>
</tr>
</table>
TA贡献1827条经验 获得超9个赞
您可以使用突变观察器。更改底部的按钮以随机将td的内部 HTML 更改为“高”:
const observer = new MutationObserver(([{target: td}]) => {
if (td.innerHTML === 'High') {
td.classList.add('high');
}
else {
td.classList.remove('high');
}
});
const tds = document.querySelectorAll('td');
tds.forEach((td, ind) => {
// add assistant CSS class
td.classList.add(`index-${ind + 1}`);
// add initial style if needed
if (td.innerHTML === 'High') {
td.classList.add('high');
}
observer.observe(td, {
characterData: false,
childList: true,
attributes: false
});
});
document.querySelector('button').addEventListener('click', () => {
const randomTdIndex = Math.floor(Math.random() * tds.length) + 1;
const td = document.querySelector(`td.index-${randomTdIndex}`);
if (td.innerHTML === 'High') {
td.innerHTML = Date.now().toString().substr(-4);
}
else {
td.innerHTML = 'High';
}
})
.high {
color: red;
}
button {
margin-top: 24px;
border: solid 2px #378ad3;
}
<table id="something">
<tr>
<th>City</th>
<th>Min.</th>
<th>Max.</th>
<th>Delay</th>
</tr>
<tr>
<td>City 1</td>
<td>$20</td>
<td>$23</td>
<td>High</td>
</tr>
<tr>
<td>City 2</td>
<td>$20</td>
<td>$23</td>
<td>High</td>
</tr>
</table>
<button>CHANGE RANDOM TD</button>
如果 HTML 不是“高”,您可能需要以相同的方式重置“红色”颜色
添加回答
举报