gpt4 book ai didi

javascript - 让一个 div 容器变得不可见

转载 作者:行者123 更新时间:2023-11-30 19:18:35 25 4
gpt4 key购买 nike

我正在尝试使用 Javascript 来显示/隐藏网页上的某个区域

如何更改下面的代码以获得所需的结果。

function yesNoCheck(marked) {
var x = document.getElementById("myDIV");
if (marked) {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
#myDIV {
width: 50%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<input type="radio" name="employee" value="Yes" id="yes" onclick="yesNoCheck(true)" checked>
<label for="yes">Yes</label>&nbsp;&nbsp;
<input type="radio" name="employee" value="No" id="no" onclick="yesNoCheck(false)">
<label for="no">No</label> <br /> <br/>
<div id="myDIV">
This is my DIV element.
</div>

当我点击"is"时,我预计蓝色区域会消失。实际上,当我点击任何一个按钮时都没有任何反应!

最佳答案

您可以使用 onchange 事件代替 onclick 来检查值更改。此外,您可以使用 document.querySelector 获取单选按钮组值,而不是将其作为参数传递。

演示

function onChangeYN() {
var x = document.getElementById("myDIV");
if (document.querySelector('input[name=employee]:checked').value == 'Yes') {
x.style.display = "none";
} else {
x.style.display = "block";
}
}

onChangeYN(); // initial call
#myDIV {
width: 50%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<input type="radio" name="employee" value="Yes" id="yes" onchange="onChangeYN()" checked>
<label for="yes">Yes</label>&nbsp;&nbsp;
<input type="radio" name="employee" value="No" id="no" onchange="onChangeYN()">
<label for="no">No</label> <br /> <br/>
<div id="myDIV">
This is my DIV element.
</div>

关于javascript - 让一个 div 容器变得不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734194/

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