Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript元素。click()不使用div标记_Javascript_Html - Fatal编程技术网

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();