这里有一个小脚本,它根据下拉列表中选择的选项显示/隐藏某些DIVs。
document.getElementById('inquiry').onchange = function() {
var i = 1;
var myDiv = document.getElementById("inquiry" + i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(("inquiry" + ++i));
}
document.getElementById(this.value).style.display = 'block';
}这个脚本基本上只是检查在下拉列表中选择了哪个值(即value="inquiry1"),然后用ID更改DIV的CSS,该ID等于下拉列表的选定值(即id="inquiry1")。
但现在,高层希望将下拉列表更改为一组具有相同功能的无线电按钮(如果选择了值为"inquiry1“的无线电按钮,则带有id="inquiry1”的div也应更改。
我将如何调整上面的脚本来安装无线电按钮?
重要的是,脚本要足够灵活,以便将来可以添加更多选项(因此可以添加"+ i“内容)。
发布于 2017-05-04 13:21:13
这里有一个使用jQuery来处理事件的解决方案(因为您用jquery标记了您的问题)。我已经包含了很多评论,以及足够的HTML和CSS,这样您就可以看到发生了什么。
需要注意的是,它没有连接许多不同的事件处理程序,每个处理程序绑定到不同的单选按钮和区段,而是只设置一个“全局”处理程序,该处理程序支持所有这些处理程序,使用单选按钮的value属性将其绑定到文档部分的id属性以显示或隐藏。
// Wire up an event handler so that any click on any radio button inside "ul.options" is monitored.
$("ul.options input:radio").on("click", function() {
// Get the "value" attribute from the radio button that was clicked.
var chosenOption = $(this).val();
// Hide all of the sections.
$(".sections > div").hide();
// Now show just the appropriate section for the button that was clicked.
$("#" + chosenOption).show();
});
// Now simulate a click on the first radio button, so *something* is shown on page load.
$("ul.options input:radio:first").click();ul.options {
display: block:
margin: 1em 0;
padding: 0;
}
ul.options li {
display: inline-block;
margin: 0 1em;
padding: 0;
}
.sections {
display: block;
border: 1px solid #CCC;
padding: 1em;
}
.sections > div {
display: none; /* Don't show any section by default */
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- These are the radio buttons you can click on. They're wrapped in label elements
so that you can click either the radio button or the text. -->
<ul class="options">
<li><label><input type="radio" value="option1" name="inquiry" /> Option 1</label></li>
<li><label><input type="radio" value="option2" name="inquiry" /> Option 2</label></li>
<li><label><input type="radio" value="option3" name="inquiry" /> Option 3</label></li>
<li><label><input type="radio" value="option4" name="inquiry" /> Option 4</label></li>
<li><label><input type="radio" value="option5" name="inquiry" /> Option 5</label></li>
</ul>
<!-- These are the sections that can be shown. Their ids must match the values
for the radio buttons. -->
<div class="sections">
<div id="option1">Here's some content for option 1</div>
<div id="option2">Here's some other content for option 2</div>
<div id="option3">Here's some different content for option 3</div>
<div id="option4">Here's yet more content for option 4</div>
<div id="option5">Here's altogether different content for option 5</div>
</div>
https://stackoverflow.com/questions/43782162
复制相似问题