Javascript元素。click()不使用div标记
出于某种原因,这段简单的代码没有勾选复选框:Javascript元素。click()不使用div标记,javascript,html,Javascript,Html,出于某种原因,这段简单的代码没有勾选复选框: <!DOCTYPE html> <html> <body> <p>Automatically tick the box</p> <form> <div id='checkingTheBox'> <div class='someValue'> <input type="checkbox" name=&qu
<!DOCTYPE html>
<html>
<body>
<p>Automatically tick the box</p>
<form>
<div id='checkingTheBox'>
<div class='someValue'>
<input type="checkbox" name="checkingTheBox">
</div>
</div>
</form>
<script type="text/javascript">
document.getElementById("checkingTheBox").click();
</script>
</body>
</html>
自动勾选该框
document.getElementById(“checkingTheBox”)。单击();
但是,当删除div
标记时,它可以正常工作。是否有任何原因导致它不能如图所示工作,以及如何让javascript在不更改HTML结构的情况下成功单击元素的建议
编辑:我尝试在
input
标记中使用id
而不是name
。这也不起作用。页面上不能有两个或多个元素具有相同的id
。id
标记应该是唯一的。此外,您不能将名称
标记用作标识
标记。这是不一样的。下面是一个代码示例,它可以根据您的需要工作:
<!DOCTYPE html>
<html>
<body>
<p>Automatically tick the box</p>
<form>
<div>
<div class='someValue'>
<input type="checkbox" id="checkingTheBox">
</div>
</div>
</form>
<script type="text/javascript">
document.getElementById("checkingTheBox").click();
</script>
</body>
</html>
您正在选择div并希望单击其内部子级上的函数,因此请尝试此脚本,该脚本将从您选择的this中选择内部子级,并在该子级上调用click函数
const div = document.getElementById('checkingTheBox');
div.firstElementChild.firstElementChild.click();
当您尝试使用
id
而不是name
时,是否也从div中删除了现在重复的id?单击
时,您希望它做什么?如果您必须“单击”document.getElementById(“checkingTheBox”)。checked=true;//取消选中document.getElementById(“checkingTheBox”)。选中=false代码>将id添加到输入中,当单击内部的div时,单击将其与当前HTML一起放入:document.getElementById(“checkingTheBox”).querySelector(“输入”).click()代码>明白了。输入
和div
的id
的重复值会使其混淆。谢谢“页面上不能有两个或多个id相同的元素”-OPs问题/代码中没有重复的id。没错,但输入中的名称标记应替换为id标记,因此我警告在这种情况下应更改或删除div中的id标记。
const div = document.getElementById('checkingTheBox');
div.firstElementChild.firstElementChild.click();