猿问

Javascript - 当值是......时更改表中的文本颜色

我有一个小问题,我是 Javascript 的初学者,我看了很多教程,但仍然找不到答案。我有一个简单的 HTML 表格,我经常在其中更改值。当 td 的值为“X”时,我希望 javascript 更改 td 中的文本颜色


例如,当 td ==“High”中的值让该特定单元格中的字体颜色为红色时。


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

更新!


所以是的,我在下面留下了效果很好的最简单的解决方案:


elements = document.getElementsByTagName("td")

for (var i = elements.length; i--;) {

  if (elements[i].innerHTML === "High") {

    elements[i].style.color = "red";

  }

  if (elements[i].innerHTML === "Medium") {

    elements[i].style.color = "orange";    

  }

  if (elements[i].innerHTML === "Low") {

    elements[i].style.color = "green";  

  }

}


绝地无双
浏览 103回答 2
2回答

智慧大石

以下是当该字段的值为 High 时将文本颜色更改为红色的示例elements = document.getElementsByTagName("td")for (var i = elements.length; i--;) {&nbsp; if (elements[i].innerHTML === "High") {&nbsp; &nbsp; elements[i].style.color = "red";&nbsp; }}<table id="something">&nbsp; <tr>&nbsp; &nbsp; <th>City</th>&nbsp; &nbsp; <th>Min.</th>&nbsp; &nbsp; <th>Max.</th>&nbsp; &nbsp; <th>Delay</th>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td>City 1</td>&nbsp; &nbsp; <td>$20</td>&nbsp; &nbsp; <td>$23</td>&nbsp; &nbsp; <td>Medium</td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td>City 2</td>&nbsp; &nbsp; <td>$20</td>&nbsp; &nbsp; <td>$23</td>&nbsp; &nbsp; <td>High</td>&nbsp; </tr></table>

素胚勾勒不出你

您可以使用突变观察器。更改底部的按钮以随机将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 不是“高”,您可能需要以相同的方式重置“红色”颜色
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答