将颜色更改为特定值

时间:2019-02-20 13:55:45

标签: javascript html html-table

我想在td的值例如为“ FAILED”时更改其背景颜色。

    <tbody>
    <template is="dom-repeat" items="{{enhancedOutput.backups}}" as="backup">
    <tr>
    <td>[[backup.myBackupName]]</td>
    <td>[[backup.size]] GiB</td>
    <td>[[backup.begin_time]]</td>
    <td>[[backup.end_time]]</td>
    <td>[[backup.total_time]] s</td>
    <td>IF THIS VALUE IS "FAILED" THEN CHANGE BACKGROUND-COLOR>[[backup.status]]</td>
   </tr>
   </template>
    </tbody>
    </table>

2 个答案:

答案 0 :(得分:2)

您可以使用多种方式执行此操作,请查看以下代码段。

  

在html中使用数据属性

td[data-content="Failed"] {
  background: red;
}
<table>
<tr>
<td data-content="Failed">Failed</td>
<td data-content="Passed">Passed</td>
</tr>
</table>

  

使用Jquery

$('td:contains("Failed")').css('background','red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Failed</td>
<td>Passed</td>
</tr>
</table>

答案 1 :(得分:0)

@Oram用户描述的关于使用类而不是data-attr的借用(不是必需的):

function triggerFailure(){ //replace this with the actual function you use to trigger the FAILED text
  var i, tdEles = document.getElementsByTagName("td");
  
  for(i=0;i<tdEles.length;i++){
    //Loop through all the elements with tag name td
    //And change their class to "failed"
    //So that the CSS code can take care of it and change the background to red
    var td = tdEles[i];
    
    //As an extra, this helps to remove formatting of where the value of the td changes from FAILED to success
    td.className = td.className.replace(/ failed/gi,"");
    
    if(td.innerHTML.toLowerCase().indexOf("failed")!= -1){ 
      //word failed has been found
      //Note that it matches any case where it can find the word "failed"
      td.className+=" failed";
    }
  }
  
}

function togglePassed(){
  document.getElementById("toToggle").innerHTML = (document.getElementById("toToggle").innerHTML=="Failed")?"Passed":"Failed";
  
  triggerFailure();
}
td{
  padding: 10px; /* just beautification */
}

td.failed{
  background: red;
  /* You can add other stuff here in case you want something more fancy than just a red background*/
}
<input type="button" onclick="triggerFailure()" value="Turn Failures red" />
<input type="button" onclick="togglePassed()" value="Toggle Failed and Passed" />
<br>

<table>
  <tr>
    <td id="toToggle">Failed</td>
    <td>Passed</td>
  </tr>
  <tr>
    <td>Just gibberish</td>
    <td>Oh no something failed!</td>
  </tr>
</table>

此外,我不知道您将td中的文本转换为“ FAILED” 的功能是什么,但是您应该在函数中调用上面的JS代码。