首页 > 解决方案 > 使用JS更改表格中单元格的行颜色

问题描述

我想根据我的标签使用纯 HTML CSS 或 JS 更改我的行颜色,而不是使用任何外部 src,因为在我想要执行此操作的应用程序中不支持它。

下面是我的代码:

table { 
  width: 750px; 
  border-collapse: collapse; 
  margin:20px auto;
}
tr:nth-of-type(even) { 
  background: #eee;
}
tr:hover {
  background-color:#f5f5f5;
}
th { 
  background: #1489b8; 
  color: white; 
  font-weight: default; 
}

td, th { 
  padding: 10px; 
  border: 3px solid #ccc; 
  text-align: center; 
  font-size: 15px;
}
h3, p{
  text-align: center;
}
<head>
  <h3>Hi User,</h3>
  <p>An alert is created. Following are the details.</p>
</head>
<table style="width:100%">
  <thead>
    <tr>
      <th> Description</th>
      <td>working</td>
    </tr>
    <tr>
      <th>Parameter</th>
      <td>Shutdown</td>
    </tr>
    <tr>
      <th>Machine </th>
      <td>ABC</td>
    </tr>
    <tr>
      <th> Type</th>
      <td>Sensor Machine</td>
    </tr>
    <tr>
      <th> Severity</th>
      <td>Low</td>
  </thead>
</table>

在此示例中,最后一个标签为“低”,我希望行颜色变为绿色。如果它读取中等,则应更改为“黄色”。有什么办法可以发生这种情况?

标签: javascripthtmlcss

解决方案


您可以简单且最简单的方法是使用Javascript querySelectorAll方法来获取td's表中的所有内容并检查它们的textContent并使用if条件应用颜色

如果条件matchesseverity级别,那么您可以使用您喜欢使用style的任何内容。background

现场工作示例:

let getTds = document.querySelectorAll('table td')

getTds.forEach(function(row) {
  //Low
  if (row.textContent == 'Low') {
    row.style.background = 'green'
  }
  //Medium
  if (row.textContent == 'Medium') {
    row.style.background = 'yellow'
  }
})
table {
  width: 750px;
  border-collapse: collapse;
  margin: 20px auto;
}

tr:nth-of-type(even) {
  background: #eee;
}

tr:hover {
  background-color: #f5f5f5;
}

th {
  background: #1489b8;
  color: white;
  font-weight: default;
}

td,
th {
  padding: 10px;
  border: 3px solid #ccc;
  text-align: center;
  font-size: 15px;
}

h3,
p {
  text-align: center;
}
<head>
  <h3>Hi User,</h3>
  <p>An alert is created. Following are the details.</p>
</head>
<table style="width:100%">
  <thead>
    <tr>
      <th> Description</th>
      <td>working</td>
    </tr>
    <tr>
      <th>Parameter</th>
      <td>Shutdown</td>
    </tr>
    <tr>
      <th>Machine </th>
      <td>ABC</td>
    </tr>
    <tr>
      <th> Type</th>
      <td>Sensor Machine</td>
    </tr>
    <tr>
      <th> Severity</th>
      <td>Low</td>
    </tr>

  </thead>

  <thead>
    <tr>
      <th> Description</th>
      <td>working</td>
    </tr>
    <tr>
      <th>Parameter</th>
      <td>Shutdown</td>
    </tr>
    <tr>
      <th>Machine </th>
      <td>ABC</td>
    </tr>
    <tr>
      <th> Type</th>
      <td>Sensor Machine</td>
    </tr>
    <tr>
      <th> Severity</th>
      <td>Medium</td>
    </tr>

  </thead>
</table>


推荐阅读