【问题标题】:jQuery:Looping all radio buttons inside an HTML tablejQuery:循环 HTML 表格中的所有单选按钮
【发布时间】:2011-02-20 13:51:13
【问题描述】:

我有一个包含 n 行的 HTML 表格,每行在 Row.Using 中包含一个单选按钮。使用 jQuery,我如何查看这些单选按钮来检查哪个单选按钮被选中?

【问题讨论】:

    标签: jquery radio-button


    【解决方案1】:

    有很多方法可以做到这一点,例如,使用.each.is 遍历方法:

    $("table tbody tr td input[name=something]:radio").each(function() {
        if($(this).is(":checked")) {
            $(this).closest("tr").css("border", "1px solid red");
        } else {
            // do something else
        }
    });
    

    【讨论】:

    • 如果你能告诉我是否可以很好地保证所有(支持 jQuery 的)浏览器都能可靠地插入缺少的 <tbody>,我会给予 +1。
    • @patrick - 不,事实并非如此。这意味着我的选择器有时会损坏。这意味着我现在将编辑此答案。该死的,但是谢谢,我以后应该多注意自己的答案:)
    【解决方案2】:

    要遍历所有选中的单选按钮,您也可以这样做:

    $('input:radio:checked').each(function() {
        //this loops through all checked radio buttons
        //you can use the radio button using $(this)
    });
    

    【讨论】:

      【解决方案3】:
      //get the checked radio input, put more specificity in the selector if needed
      var $checkedRadio = $("input[type=radio]:checked");
      
      //if you want the value of the checked radio...
      var checkedRadioVal = $checkedRadio.val();
      

      【讨论】:

        【解决方案4】:
        var checked = $('#table :radio:checked');
        

        【讨论】:

          【解决方案5】:
          $("table tr input[type=radio]:checked");
          

          【讨论】:

            【解决方案6】:

            您想处理每个单选按钮还是只需要选中的单选按钮?如果是后者,那就很简单了:

            $('table input:radio:checked')
            

            参考::radio:checked

            【讨论】:

            • +1。 Afaik jQuery 的查找是从右到左的,所以如果唯一的条件是它们需要在一个表中,那么整个 thead tr td 是不必要的。在这种情况下,:radio:checked 是最“优雅”的选择器。
            【解决方案7】:
            $('.my-radio-class:checked')
            

            http://api.jquery.com/checked-selector/

            【讨论】:

              【解决方案8】:
              $('#table tbody tr input[type=radio]').each(function(){
               alert($(this).attr('checked'));
              });
              

              HTH。

              【讨论】:

              • #table > tr 会在喜欢添加自己的tbody 元素的某些浏览器(chrome/firefox)上阻塞,而#table tr 不会。
              猜你喜欢
              • 1970-01-01
              • 2016-09-28
              • 1970-01-01
              • 1970-01-01
              • 2013-09-12
              • 1970-01-01
              • 2014-08-15
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多