首页 > 解决方案 > HTML 表上的“querySelectorAll”未按预期工作

问题描述

我的任务是在 HTML 表 tr 元素上使用 querySelectorAll ,使用 nth-child 为偶数和奇数打印不同的颜色,但只有偶数有效。我的代码如下

我也收到“未捕获的类型错误:无法读取未定义的属性'样式'”的错误,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table>
    <thead>
        <tr>
        <th>Numbers</th>
        </tr>
    </thead>
    <tbody>
        <tr>
        <td>1 = odd</td>
        </tr>
        <tr>
        <td>2 = even</td>
        </tr>
        <tr>
        <td>3 = odd</td>
        </tr>
        <tr>
        <td>4 = even</td>
        </tr>
    </tbody>
    </table>
    <button onclick='execute()'>Execute</button>
</body>
<script>
    function execute() {
        // your code goes here
    var odd = document.querySelectorAll("tbody tr:nth-child(odd)")
    var even = document.querySelectorAll("tbody tr:nth-child(even)")
for(i = 0; i<= odd.length; i++){
  odd[i].style.backgroundColor = "red"
}
for(i = 0; i<= even.length; i++){
  even[i].style.backgroundColor = "green"
}
    }

</script>
</html>

标签: javascripthtmlcssnode.jsreactjs

解决方案


您想要i < odd.length而不是i <= odd.length(以及对偶数的相同更改)。length将是最后一个索引加一,因为数组索引是从零开始的。

超出数组末尾会导致错误,这会停止执行,因此您看不到任何否则会发生的更改。

仅适用于这些更改。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table>
    <thead>
        <tr>
        <th>Numbers</th>
        </tr>
    </thead>
    <tbody>
        <tr>
        <td>1 = odd</td>
        </tr>
        <tr>
        <td>2 = even</td>
        </tr>
        <tr>
        <td>3 = odd</td>
        </tr>
        <tr>
        <td>4 = even</td>
        </tr>
    </tbody>
    </table>
    <button onclick='execute()'>Execute</button>
</body>
<script>
    function execute() {
        // your code goes here
    var odd = document.querySelectorAll("tbody tr:nth-child(odd)")
    var even = document.querySelectorAll("tbody tr:nth-child(even)")
for(i = 0; i< odd.length; i++){
  odd[i].style.backgroundColor = "red"
}
for(i = 0; i< even.length; i++){
  even[i].style.backgroundColor = "green"
}
    }

</script>
</html>


推荐阅读