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在工作,另一个在工作。
答案 0 :(得分:1)
提供不同的ID。它将起作用。
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";
}}
function myFunction1(){
var checkBox = document.getElementById("myCheck1");
var text1 = document.getElementById("text1");
if (checkBox.checked == true){
text1.style.display = "block";
} else {
text1.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="myCheck1" onclick="myFunction1()">
<p id="text1" style="display:none">Checkbox 2 is CHECKED!</p>
答案 1 :(得分:0)
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";
}
}