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

查看:93
本文介绍了如何使用 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天全站免登陆