【问题标题】:Check Radio Button when clicking DIV单击 DIV 时检查单选按钮
【发布时间】:2009-07-17 20:27:51
【问题描述】:

我正在使用 php / jquery 编写一个测验应用程序。答案选择包含如下:

<ul id="answers"> 
    <li> 
        <div> 
        <input type='radio' name='answer_id' value='313'> True
        </div> 
    </li> 
    <li> 
        <div> 
        <input type='radio' name='answer_id' value='314'> False
        </div> 
    </li> 
</ul> 

在使用 css 设置样式后,这些答案会出现在一个容器中,每行一个答案。每个答案在容器内都有自己的盒子。我希望用户能够单击单个答案 div 内的任何位置并选中单选。

当用户单击单选按钮的容器 div 时,如何使用 jquery 激活单选按钮检查?

【问题讨论】:

标签: jquery html


【解决方案1】:

我同意 tj111,但如果并不总是适合:

  • 样式更难。
  • 标签只有在其中包含文本时才有效(感谢 Michael)

这是使用 div 和 jQuery 的替代代码:

$('input:radio').click(ev){
    ev.stopPropagation();
}).parent().click(function(ev){
    ev.preventDefault();
    $(this).children('input').click();
    $(this).addClass('active').siblings().removeClass('active');
});

现在有了“活动”类,您甚至可以隐藏收音机并使用样式表突出显示。

【讨论】:

  • 这……很有趣。怎么样: $('input:radio').click(function (ev) { ev.stopPropagation(); }).parent().click(function (ev) { ev.preventDefault(); $(this). children('input').click(); });
  • 我发现标签只有在有文本(或大量空白)可供点击时才有效。相反,将点击放在父级上会搞砸实际的无线电点击本身。修改 romaninsh 的代码解决了我的问题
【解决方案2】:

这一切都可以在原生 HTML 中使用 &lt;label&gt; 元素完成,而不是使用 jQuery。 Here is a sample 在行动中。

<ul id="answers"> 
        <li> 
                <label> 
                    <input type='radio' name='answer_id' value='313'> True
                </label> 
        </li> 
        <li> 
                <label> 
                    <input type='radio' name='answer_id' value='314'> False
                </label> 
        </li> 
</ul>

【讨论】:

    【解决方案3】:

    label标签的正确用法是:

    <input type="checkbox" id="checkme" name="checkme" /> <label for="checkme">Toggle this checkbox on/off</label>
    

    for="..." 总是引用输入的 id。

    【讨论】:

      【解决方案4】:

      可能是这样的:

      $('#answers li div').click(function(){
      
        var r = $(this).find('input[type=radio]');
        if($(r).is(":checked"))
        {
          $(r).attr("checked", "");
        }
        else
        {
          $(r).attr("checked", "checked");
        }
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-26
        • 2014-04-09
        • 1970-01-01
        • 2023-03-27
        • 2013-03-16
        • 2013-04-05
        • 2019-05-29
        相关资源
        最近更新 更多