jQuery和If语句取消选择单选按钮

时间:2011-04-01 00:21:24

标签: javascript jquery

好吧,我已经被困住了,现在已经敲了一会儿,试图弄清楚我做错了什么。

情景:

我有一个带有是/否答案的问题(即2个单选按钮)。当用户选择是或否时,我调用一个函数来.toggle()一个隐藏的div来显示一个链接。这很好用。如果他们返回并再次检查是/否,则由于.toggle()

而再次消失

我的问题是,如果用户点击否(并显示链接),然后点击“是”,我希望由于“无结果”而显示的链接消失,反之亦然。

所以基本上一次只显示1个链接。

我认为也许一个If语句会起作用,但我似乎无法做到正确。

我的代码:

<div id="Question1">
  <div>Do you kazoo?</div>
  <input type="radio" ID="Q1RB1" runat="server" value="Yes" text="Yes" name="RadioGroup1"/>Yes<br />
  <input type="radio" ID="Q1RB2" runat="server" value="No" text="No" name="RadioGroup1"/> No
  <span id="Q1RB1Results" style="display:none">&nbsp; &nbsp; <a href=#>Click here</a></span>  
  <span id="Q1RB2Results" style="display:none">&nbsp; &nbsp; <a href=#>Click here</a></span>
 </div>

我的jQuery代码适用于每个单独的单选按钮:

    $("input[id$=Q1RB1]:radio").change(function () {
        $("[id$=Q1RB1Results]").toggle();
    });

    $("input[id$=Q1RB2]:radio").change(function () {
        $("[id$=Q1RB2Results]").toggle();

    });    

这是我试图开始工作的If语句。艾米,我这样做错了吗?

    if ($("input[id$=Q1RB2]").is(":checked")) {
        $("input[id$=Q1RB2]:radio").change(function () {
            $("[id$=Q1RB2Results]").toggle();
        });
    });

感谢您的任何想法/建议。我在Stackoverflow和'网上尝试了很多答案,但似乎无法弄清楚我做错了什么。 :(
〜Ⅴ类

更新:我在JSFiddle上放了一个示例表单和对话框。 http://jsfiddle.net/Valien/7uN6z/4/ 我尝试了一些这里提到的解决方案但无法让它们正常工作,所以不确定我做错了什么。

3 个答案:

答案 0 :(得分:0)

当您在JQuery(.change,.click,.blur等)中注册事件侦听器时,Javascript引擎会匹配选择器并在此时应用它们。考虑到这一点,你可以重新安排你的代码(这是接近正确的),这应该做的伎俩:

/* The function you're about to define applies to all radio button 
   inputs whose ID ends with Q1RB2 */
$("input[id$=Q1RB2]:radio").change(function()
{
    /* Inside the change function, $(this) refers to the instance that
       was changed. So, this checks to see if the instance that was just 
       changed is currently checked, after being changed. */
    if ($(this).is(":checked"))
    {
        // If that was the case, then toggle the item
        $("[id$=Q1RB2Results]").toggle();
    }
}); 

答案 1 :(得分:0)

试试这个:

$('input:radio[name=RadioGroup1]').change(function(){
    var show = "#" + $(this).attr('id') + 'Results';
    $('#Question1 span').hide();
    $(show).show();
});

答案 2 :(得分:0)

我相信这就是你所需要的:


// declare common variables so it's easier to target
var question = $("#Question1"),
    group = question.find("input[name='RadioGroup1']"),
    span = question.find("span");

// change listener for each radio button group
group.click(function(){ 
    var id = $(this).attr("id"); // get the radio button id for reference
    span.each(function(){ // loop through each span and check which one to hide/show
        var item = $(this);
        if (item.attr("id")===id+"Results") { item.show(); } else { item.hide(); }
    });
});
相关问题