JavaScript / 显示隐藏 Div > 选中单选按钮时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15514760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript / Show Hide Div > When Radio Button Checked
提问by Brandrally
I am just wanting to have a div display if a radio box is selected. It's seems simple and most tutes online are for two options, where in my instance I have three.
如果选择了单选框,我只想显示 div。这看起来很简单,大多数在线课程都有两个选项,在我的例子中我有三个。
The logic on this has just been lost on me. Any help would be greatly appreciated.
我刚刚失去了这方面的逻辑。任何帮助将不胜感激。
<!-- // Javascript // -->
<script language="JavaScript" type="text/javascript">
function showhidediv(rad){
var rads=document.getElementsByName(rad.name);
document.getElementById('one').style.display=(rads[1].checked)?'block':'none' ;
document.getElementById('two').style.display=(rads[2].checked)?'block':'none' ;
document.getElementById('three').style.display=(rads[3].checked)?'block':'none' ;
}
</script>
<form name="create" id="create" method="post" enctype="multipart/form-data">
<input name="pagetype" type="radio" value="1" onclick="showhidediv(this);"/>One <br />
<input name="pagetype" type="radio" value="2" onclick="showhidediv(this);"/>two<br>
<input name="pagetype" type="radio" value="3" onclick="showhidediv(this);"/>three<br>
<div id="one" class="CF" style="display:none;" >One </div>
<div id="two" style="display:none;" class="CF" >Two</div>
<div id="three" style="display:none;" class="CF" >Three</div>
</form>
回答by Prasath K
<script language="JavaScript" type="text/javascript">
function showhidediv(rad){
var rads=document.getElementsByName(rad.name);
document.getElementById('one').style.display=(rads[0].checked)?'block':'none' ;
document.getElementById('two').style.display=(rads[1].checked)?'block':'none' ;
document.getElementById('three').style.display=(rads[2].checked)?'block':'none' ;
}
</script>
Use this .. The thing i modified is
使用这个..我修改的东西是
rads is an array so the first element has an index 0
rads 是一个数组,因此第一个元素的索引为 0
回答by Sharun
Radio button index start with 0.
单选按钮索引从 0 开始。
Modify:
调整:
function showhidediv( rad )
{
var rads = document.getElementsByName( rad.name );
document.getElementById( 'one' ).style.display = ( rads[0].checked ) ? 'block' : 'none';
document.getElementById( 'two' ).style.display = ( rads[1].checked ) ? 'block' : 'none';
document.getElementById( 'three' ).style.display = ( rads[2].checked ) ? 'block' : 'none';
}