如何用JS装饰表格单元格

问题描述 投票:0回答:1

如何使用javascript装饰html中的单元格?

我在 html 中有这张表

<table border="1" width="300" height="200">
        <tr>
            <td id="11"><</td>
            <td id="12"></td>
            <td id="13"></td>
            <td id="14"></td>
            <td id="15"></td>
            <td id="16"></td>
            <td id="17"></td>
            <td id="18"></td>
            <td id="19"></td>
            <td id="20"></td>
        </tr>
</table>
<style>
        table {
            border-collapse: collapse;
        }
        td {
            border: 1px solid grey;>
        }
    </style>

我想有条件地获取cell id 11,并将其涂黑

我尝试在 JS 上做,但没有任何效果

function bthClick(){
    let table = document.querySelectorAll('td id')
    table[11].style.color = 'dark'
}
javascript html css node.js
1个回答
1
投票

要获取 ID 为 11 的单元格,请使用

document.querySelector('td[id="11"]')
,并注意深色在
CSS
中不是有效的颜色值,请改用黑色。

function bthClick() {
  // select the cell with id "11"
  let cell = document.querySelector('td[id="11"]'); 
  
  // set its background color to black and text color to white
  cell.style.backgroundColor = 'black'; 
  cell.style.color = 'white'; 
}
table {
    border-collapse: collapse;
    margin-top: 10px;
}
td {
    border: 1px solid grey;
}
<button onclick="bthClick()">Decorate Table</button>

<table border="1" width="300" height="200">
        <tr>
            <td id="11">11</td>
            <td id="12">12</td>
            <td id="13">13</td>
            <td id="14">14</td>
            <td id="15">15</td>
            <td id="16">16</td>
            <td id="17">17</td>
            <td id="18">18</td>
            <td id="19">19</td>
            <td id="20">20</td>
        </tr>
</table>

© www.soinside.com 2019 - 2024. All rights reserved.