gpt4 book ai didi

javascript - 为什么我的 JavaScript DOM 遍历不起作用?

转载 作者:行者123 更新时间:2023-11-28 15:35:46 25 4
gpt4 key购买 nike

我的表单上有两个复选框。当有人选中第二个框时,我的 JavaScript 会进行检查以确保选中第一个框。如果第一个框没有被选中,那么我的 JavaScript 会检查它。然而,由于某种原因,我的 DOM 遍历无法正常工作,并且第一个框没有被选中;相反,我在第 10 行(“if”语句)收到“TypeError:firstCheckbox is null”。为什么这不起作用?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
function setMe(secondCheckbox){
// alert(secondCheckbox.parentNode.previousSibling.nodeName);
var firstCheckbox = secondCheckbox.parentNode.previousSibling.lastChild;
if(secondCheckbox.checked && !firstCheckbox.checked){
firstCheckbox.checked = true;
}
}
</script>
</head>
<body>
<div>
<form>
<table border="1" cellspacing="4" cellpadding="4">
<thead>
<tr>
<th>
<label for="input01">input01</label><br>
<input type="text" id="input01" name="input01">
</th>
<th>
<label for="input02">input02</label><br>
<input type="text" id="input02" name="input02">
</th>
<th>
<label for="input03">input03</label><br>
<input type="checkbox" id="input03" name="input04">
</th>
<th>
<label for="input04">input04</label><br>
<input type="checkbox" id="input04" name="input04" onChange="setMe(this);">
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">
<button type="submit">submit</button>
</td>
<td colspan="2">
<button type="reset">reset</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>

最佳答案

简而言之,previousSibling 并不意味着 previousSiblingElement,而是意味着 previousSiblingNode,对于 lastChild 也是如此。

您需要更改代码以避免根据 html 文件的格式自动添加文本节点。

为您提供的示例遍历如下(我尚未对此进行测试/调试,只是在此处的编辑器中输入):

var prev = secondCheckbox.parentNode.previousSibling;
while (prev.nodeType !== Node.ELEMENT_NODE) {
prev = prev.previousSibling;
}
// prev now points to the previousElementSibling
var lastChild = prev.lastChild;
while (lastChild.nodeType !== Node.ELEMENT_NODE) {
lastChild = lastChild.previousSibling;
}

// lastChild should have the element you're looking for

关于javascript - 为什么我的 JavaScript DOM 遍历不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25673760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com