根据单选按钮单击显示和隐藏div [英] show and hide divs based on radio button click

查看:479
本文介绍了根据单选按钮单击显示和隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用单选按钮和jQuery动态更改显示的div-HTML:

I want to be able to dynamically change what divs are show using radio button and jQuery - 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并不满意.

This does nothing , the divs always show. Im sure this is simple, but Im poor at jQuery .

推荐答案

您处在正确的轨道上,但是您忘记了两件事:

You're on the right track, but you forgot two things:

  1. desc类添加到您的描述divs
  2. input具有数字值,而id具有文本.
  1. add the desc classes to your description divs
  2. You have numeric values for the input but text for the id.

我已经修复了上述问题,并且还在第三说明div的开头hide()添加了一行.

I have fixed the above and also added a line to initially hide() the third description div.

查看实际操作- http://jsfiddle.net/VgAgu/3/

<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();
    });
});

这篇关于根据单选按钮单击显示和隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆