参见英文答案 >
How to use jQuery to show/hide divs based on radio button selection?6个
我希望能够使用单选按钮和jQuery动态更改显示div的内容 – HTML:
我希望能够使用单选按钮和jQuery动态更改显示div的内容 – HTML:
<div id="myRadioGroup"> 2 Cars<input type="radio" name="cars" checked="checked" value="2" /> 3 Cars<input type="radio" name="cars" value="3" /> <div id="twoCarDiv"> 2 Cars Selected </div> <div id="threeCarDiv"> 3 Cars </div> </div>
和jQuery:
<script>
$(document).ready(function(){
$("input[name$='cars']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#"+test).show();
});
});
</script>
这没什么,div总是表现出来.我确定这很简单,但我在jQuery很差.
解决方法
你走在正确的轨道上,但你忘记了两件事:
>将desc类添加到描述div中
>您有输入的数值,但ID有文本.
我已经修复了上面的内容并且还添加了一行来初始化hide()第三个描述div.
检查一下 – http://jsfiddle.net/VgAgu/3/
HTML
<div id="myRadioGroup">
2 Cars<input type="radio" name="cars" checked="checked" value="2" />
3 Cars<input type="radio" name="cars" value="3" />
<div id="Cars2" class="desc">
2 Cars Selected
</div>
<div id="Cars3" class="desc" style="display: none;">
3 Cars
</div>
</div>
JQuery的
$(document).ready(function() {
$("input[name$='cars']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#Cars" + test).show();
});
});