【发布时间】:2021-06-21 18:08:51
【问题描述】:
我的任务是在 HTML 表 tr 元素上使用 querySelectorAll,使用 nth-child 为偶数和奇数打印不同的颜色,但只有偶数有效。下面是我的代码
我也收到“Uncaught TypeError: Cannot read property 'style' of undefined”的错误,
<!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>
【问题讨论】:
标签: javascript html css node.js reactjs