gpt4 book ai didi

javascript - 复选框不适用于多个复选框 onclick

转载 作者:行者123 更新时间:2023-12-02 22:34:41 25 4
gpt4 key购买 nike

function myFunction(){
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}}
Checkbox 1: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox 1 is CHECKED!</p>
<br>
Checkbox 2: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox 2 is CHECKED!</p>

我希望两个复选框在逐个单击后都可以工作。我得到的结果:只有复选框 1 有效,另一个无效。

最佳答案

id 属性必须是唯一的,因此在本例中 getElementById 仅选择第一个元素。您可以将 id 属性更改为 class,然后使用 getElementsByClassName 选择复选框和段落。

Checkbox 1: <input type="checkbox" class="myCheck" onclick="myFunction()">

<p class="text" style="display:none">Checkbox 1 is CHECKED!</p>
<br>
Checkbox 2: <input type="checkbox" class="myCheck" onclick="myFunction()">

<p class="text" style="display:none">Checkbox 2 is CHECKED!</p>

现在 JavaScript 部分需要识别复选框。我们应该添加一个 FOR 循环来选择复选框[i] 及其下面的段落。

for (var i=0;i<checkBox.length; i++) {
if (checkBox[i].checked == true){
text[i].style.display = "block";
} else {
text[i].style.display = "none";
}
}

See the Demo here

关于javascript - 复选框不适用于多个复选框 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58778361/

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