我想制作一个交互式在线表格。当人们选择第一个问题的一个选项时,相应元素将在选择时显示,并在选择另一个选项时隐藏。 (选择其他按钮时应显示其他元素)
这是我目前的代码。
function showStuff(id, btn) {
if (document.getElementById(id).style.display == "none") {
document.getElementById(id).style.display = 'block';
} else if (document.getElementById(id).style.display == 'block') {
document.getElementById(id).style.display = 'none';
}
}
<input name="q1" type="radio" value="A" onchange="showStuff('A', this); return false;" />
<input name="q1" type="radio" value="B" onchange="showStuff('B', this); return false;" />
<div id="A" style="display:none">
This should display only when A button is clicked
</div>
<div id="B" style="display:none">
This should display only when B button is clicked
</div>
一旦我显示它,当我选择其他选项时就无法隐藏它。请问你有什么好的建议吗?非常感谢!
最佳答案
您就快完成了..只需添加一行代码即可在每次点击时隐藏两个 div。
使用 jQuery:
$("#A,#B").hide();
没有 jQuery:
document.getElementById("A").style.display = 'none';
document.getElementById("B").style.display = 'none';
请参阅下面的完整工作代码:
function showStuff(id, btn) {
$("#A,#B").hide(); // hide both each time
document.getElementById(id).style.display = 'block';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="q1" type="radio" value="A" onchange="showStuff('A', this); return false;" />
<input name="q1" type="radio" value="B" onchange="showStuff('B', this); return false;" />
<div id="A" style="display:none">
This should display only when A button is clicked
</div>
<div id="B" style="display:none">
This should display only when B button is clicked
</div>
关于javascript - 如何在选择单选按钮时显示元素并在未使用 javascript 选择时隐藏它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39466305/