gpt4 book ai didi

javascript - 单击复选框时隐藏/显示 div

转载 作者:行者123 更新时间:2023-12-03 01:15:29 25 4
gpt4 key购买 nike

你好,我只是想在复选框上隐藏/显示div,单击我已经尝试了下面的代码/脚本,但它不起作用?我还想知道是否有更简单的方法来做到这一点?

function checkBox1() {    
var checkBox = document.getElementById("myCheck1");
var text = document.getElementsByClassName("shop");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}

function checkBox2() {
var checkBox = document.getElementById("myCheck2");
var text = document.getElementsByClassName("party");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}

function checkBox3() {
var checkBox = document.getElementById("myCheck3");
var text = document.getElementById("dailyquests");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<center>| Shop: <input type="checkbox" id="myCheck1" onclick="checkBox1()" checked> | Party: <input type="checkbox" id="myCheck2" onclick="checkBox2()" checked> | Dailyquests: <input type="checkbox" id="myCheck3" onclick="checkBox3()" checked> |</center>
<br>
<br>
<div class="shop">TEXT HERE</div>
<br>
<div class="party">TEXT HERE</div>
<br>
<div class="dailyquests">TEXT HERE</div>

抱歉,如果我的英语不好

最佳答案

document.getElementsByClassName 返回元素列表。文本对象位于第一个元素中:

function checkBox1() {    
var checkBox = document.getElementById("myCheck1");
var text = document.getElementsByClassName("shop")[0];
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}

function checkBox2() {
var checkBox = document.getElementById("myCheck2");
var text = document.getElementsByClassName("party")[0];
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}

function checkBox3() {
var checkBox = document.getElementById("myCheck3");
var text = document.getElementsByClassName("dailyquests")[0];
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<center>| Shop: <input type="checkbox" id="myCheck1" onclick="checkBox1()" checked> | Party: <input type="checkbox" id="myCheck2" onclick="checkBox2()" checked> | Dailyquests: <input type="checkbox" id="myCheck3" onclick="checkBox3()" checked> |</center>
<br>
<br>
<div class="shop">TEXT HERE</div>
<br>
<div class="party">TEXT HERE</div>
<br>
<div class="dailyquests">TEXT HERE</div>

关于javascript - 单击复选框时隐藏/显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52035561/

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