【问题标题】:Radio buttons - show DIV based on checked button with jQuery单选按钮 - 使用 jQuery 显示基于选中按钮的 DIV
【发布时间】:2010-08-02 10:19:44
【问题描述】:

我正在尝试实现以下目标 - 从一个问题列表中,每个问题都有 4 个多项选择答案,我需要在按下单选按钮后显示用户是否正确回答(立即) .

这是一个问题的例子:

<ol>
<li id="question_one">
<p><input type="radio" name="question_1" value="answer_1" />Corn</p>
<p><input type="radio" name="question_1" value="answer_2" />Cotton</p>
<p><input type="radio" name="question_1" value="answer_3" />Rice</p>
<p><input type="radio" name="question_1" value="answer_4" />Soybeans</p>
</li>
</ol>

<div id="q1_answer_1" class="show_answer">Corn 11.0%</div>
<div id="q1_answer_2" class="show_answer">Cotton 2.5%</div>
<div id="q1_answer_3" class="show_answer">Rice 11.0%</div>
<div id="q1_answer_4" class="show_answer">Soybeans 7.0%</div>

以及生成的 jquery:

$("#question_one input:radio:eq(answer_1)").click(function(){
$("#q1_answer_1").show(100);
});

$("#question_one input:radio:eq(answer_2)").click(function(){
$("#q1_answer_2").show(100);
});

$("#question_one input:radio:eq(answer_3)").click(function(){
$("#q1_answer_3").show(100);
});

$("#question_one input:radio:eq(answer_4)").click(function(){
$("#q1_answer_4").show(100);
});

我相信这不起作用,因为eq() 仅适用于数值?是否有等效于 eq() 的输入值?或者关于上述如何工作的任何其他建议?

非常感谢

【问题讨论】:

    标签: jquery forms radio-button


    【解决方案1】:

    如果你想让它更通用一点,你可以根据值来做,像这样:

    $("#question_one :radio[name=question_1]").change(function() {
        $("div.show_answer").hide();
        $("#q1_" + $(this).val()).show(100);
    });​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

    You can give it a try here,或者如果你需要更通用的,假设你有多个问题,只需将上面的每个 HTML 块包装在一个容器中,例如&lt;div class="question"&gt;&lt;/div&gt;,然后你可以这样做:

    $(".question :radio[name=question_1]").change(function() {
        $(this).closest(".question").find("div.show_answer").hide()
               .filter("[id$='" + $(this).val() +"']").show(100);
    });​
    

    You can test that version here,它可以解决多个问题,而无需为每个问题复制代码。


    对于 cmets: 要在第一次单击后终止它,您有几个选项,您可以通过将其添加到处理程序来禁用它们 (test here):

    $(this).closest('li').find(':radio').attr('disabled', true);
    

    或者,如果您想启用更改但不再显示答案,只需解除绑定 (test here):

    $(this).closest('li').find(':radio').unbind('change');
    

    【讨论】:

    • 这太好了,谢谢!唯一的事情是,用户可以选中一个单选框,查看隐藏 DIV 的内容,然后按另一个,然后查看该 DIV 的内容等。有没有什么办法可以修改为只需单击第一个单选按钮,显示 DIV,然后不再接受单选?
    • @Dave - 是的,添加到答案中,我给了你两个选项,你可以禁用它们以防止选择更改只是取消绑定处理程序以便选择可以更改但显示的 div 没有。
    【解决方案2】:

    尝试使用伪选择器 :checked,如下所示: $("#question_one input:checked")....

    【讨论】:

    • 谢谢@Calle,但我选择了尼克的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 2013-10-30
    • 1970-01-01
    • 2017-04-28
    • 2019-03-19
    • 2012-09-05
    相关资源
    最近更新 更多