jQuery 使用单选按钮切换 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4674020/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:41:57  来源:igfitidea点击:

jQuery toggle div with radio buttons

jquerytoggle

提问by Dooie

Simple html & jQuery

简单的 html 和 jQuery

<label><input id="rdb1" type="radio" name="toggler" value="1" />Money</label>
<label><input id="rdb2" type="radio" name="toggler" value="2" />Interest</label>

<div id="blk-1" style="display:none">
    ...
</div>
<div id="blk-2" style="display:none">
    ...
</div>

$(function() {
    $("[name=toggler]").each(function(i) {
        $(this).change(function(){
            $('#blk-1, #blk-2').hide();
            divId = 'blk-' + $(this).val();
            $("#"+divId).show('slow');
        });
    });
 });

The desired toggle effect does not work though. Clicking one radio box fails to hide the other.

但是,所需的切换效果不起作用。单击一个单选框无法隐藏另一个。

Any Ideas?

有任何想法吗?

回答by davin

<label><input id="rdb1" type="radio" name="toggler" value="1" />Money</label>
<label><input id="rdb2" type="radio" name="toggler" value="2" />Interest</label>

<div id="blk-1" class="toHide" style="display:none">
    money
</div>
<div id="blk-2" class="toHide" style="display:none">
    interest
</div>

$(function() {
    $("[name=toggler]").click(function(){
            $('.toHide').hide();
            $("#blk-"+$(this).val()).show('slow');
    });
 });

as in http://www.jsfiddle.net/eKFrW/

http://www.jsfiddle.net/eKFrW/

回答by amosrivera

$("input:radio").click(function(){
    $("div").hide();
    var div = "#blk-"+$(this).val();
    $(div).show();
});

Online demo here: http://jsfiddle.net/yLJPC/

在线演示在这里:http: //jsfiddle.net/yLJPC/

回答by stephen776

Heres what you want I think. To start I would make the first radio button selected and the first div visible. Then switching buttons would swap the divs

继承人你想要什么我想。首先,我将选择第一个单选按钮并使第一个 div 可见。然后切换按钮将交换 div

$("input:radio").click(function(){        
   $('#blk-1').toggle(); 
    $('#blk-2').toggle(); 
});