javascript - 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>
解决方案
您想要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>
推荐阅读
- javascript - 获取不同域 iframe 内容的大小
- c - 如何使用 void 指针通过多个级别将多个结构作为同一参数传递
- java - 编写一个名为 isPrime 的方法,它接受一个整数作为参数,如果参数是素数则返回 true
- ios - Swift:nskeyedunachiver 失败并以 'NSInvalidArgumentException' 终止应用程序,原因:'-[__NSCFData count]
- kotlin - 如何在 kotlin 中使用另一个列表过滤和排序列表
- asp.net-core - 缓存标签助手,具有可变路由属性
- java - 如何发布一个android库?Android Maven 发布插件
- regex - 正则表达式负前瞻无法正常工作
- javascript - 如何使用 NodeJS 脚本加载 JSON 文件?- 需要读取和上传目录中的所有 JSON 文件,文件之间可能会暂停
- python - 2D 中的单调插值