如何使用jQuery基于单选按钮选择显示/隐藏div? [英] How to use jQuery to show/hide divs based on radio button selection?

查看:303
本文介绍了如何使用jQuery基于单选按钮选择显示/隐藏div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些单选按钮,并且我希望根据选择哪个单选按钮来显示不同的隐藏div. HTML如下所示:

I have some radio buttons and I'd like to have different hidden divs show up based on which radio button is selected. Here's what the HTML looks like:

<form name="form1" id="my_form" method="post" action="">
    <div><label><input type="radio" name="group1" value="opt1">opt1</label></div>  
    <div><label><input type="radio" name="group1" value="opt2">opt2</label></div>  
    <div><label><input type="radio" name="group1" value="opt3">opt3</label></div>  
    <input type="submit" value="Submit">
</form>

....

<style type="text/css">
    .desc { display: none; }
</style>

....

<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc">consectetur adipisicing</div>
<div id="opt3" class="desc">sed do eiusmod tempor</div>

这是我的jQuery:

And here's my jQuery:

$(document).ready(function(){ 
    $("input[name$='group2']").click(function() {
        var test = $(this).val();
        $("#"+test).show();
    }); 
});

之所以这样做,是因为我的单选按钮和div是动态生成的(单选按钮的值将始终具有一个对应的div).上面的代码部分起作用-div将在选中正确的按钮时显示,但是我需要添加一些代码以使div在按钮未被选中后再次隐藏.谢谢!

The reason I'm doing it that way is because my radio buttons and divs are being generated dynamically (the value of the radio button will always have a corresponding div). The code above works partially - the divs will show when the correct button is checked, but I need to add in some code to make the divs hide again once the button is unchecked. Thanks!

推荐答案

更新2015/06

自问题发布以来jQuery不断发展,现在推荐的方法是使用$.on

As jQuery has evolved since the question was posted, the recommended approach now is using $.on

$(document).ready(function() {
    $("input[name=group2]").on( "change", function() {

         var test = $(this).val();
         $(".desc").hide();
         $("#"+test).show();
    } );
});

或在$.ready()

$(document).on( "change", "input[name=group2]", function() { ... } );

原始答案

您应该使用.change()事件处理程序:

You should use .change() event handler:

$(document).ready(function(){ 
    $("input[name=group2]").change(function() {
        var test = $(this).val();
        $(".desc").hide();
        $("#"+test).show();
    }); 
});

应该工作

这篇关于如何使用jQuery基于单选按钮选择显示/隐藏div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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