亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用JS更改表格中單元格的行顏色

使用JS更改表格中單元格的行顏色

呼喚遠方 2023-02-24 15:26:32
我想根據我的標簽使用純 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>在此示例中,最后一個標簽顯示為“低”,我希望行顏色變為綠色。如果它讀取介質,它應該變為“黃色”。這有可能發生嗎?
查看完整描述

1 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

您可以簡單且最簡單的方法是使用Javascript querySelectorAll方法獲取td's表中的所有內容并檢查它們的textContentif并使用條件應用顏色

如果條件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>


查看完整回答
反對 回復 2023-02-24
  • 1 回答
  • 0 關注
  • 230 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號