【问题标题】:How Can I get the text of the selected radio in the radio groups如何在电台组中获取所选电台的文本
【发布时间】:2011-01-09 02:21:24
【问题描述】:

正如标题中所说 例如:

<input id="User_Type_0" type="radio" name="User_Type" value="1" checked="checked" />
<label for="User_Type_0">User1</label>
<input id="User_Type_1" type="radio" name="User_Type" value="2" />
<label for="User_Type_1">User2</label>

如何获取文本:用户 1

【问题讨论】:

    标签: jquery text radio-button checked


    【解决方案1】:

    $('input:radio:checked').siblings('label:first').html()


    更新:

    正如 Victor 在 cmets 部分中指出的,前一个选择器将始终选择第一个标签。 next 函数应该可以工作:

    $('input:radio:checked').next('label:first').html()
    

    【讨论】:

    • 如果 html 元素的顺序发生变化,你就完蛋了 :-)
    • 这总是选择 DOM 顺序中的第一个标签,而不是下一个!
    • @Victor,你是对的。感谢您指出了这一点。我已经更新了我的答案。
    【解决方案2】:

    这个怎么样?

    var forLabel = $('input:radio:checked').attr("id");
    $("label[for='" + forLabel + "']").text();
    

    【讨论】:

    • 好一般的想法,但您需要使用不同的变量名 – for 是保留字。
    • 如果多于1个组,可以通过单选按钮的name-属性选择需要的组
    【解决方案3】:

    使用.next();

    $("input:radio:checked").next().text();
    

    【讨论】:

      【解决方案4】:

      使用下一个Adjacent Selector, +怎么样?

      $('input:radio:checked + label').text();
      

      这是一个Working Demo

      【讨论】:

        【解决方案5】:

        这对我有用(我正在使用 jQuery Mobile):

        var value = $(":radio[name=location]:checked").val();
        var text = $(":radio[name=location]:checked").prev("label").text();
        

        用于此的 DOM:

        <div id="locations" data-role="controlgroup" class="ui-controlgroup ui-controlgroup-vertical ui-corner-all">
           <div class="ui-controlgroup-controls ">
              <div class="ui-radio">
                 <label for="location0" class="ui-btn ui-corner-all ui-btn-inherit ui-btn-icon-left ui-radio-off ui-first-child">1439</label>
                 <input type="radio" name="location" id="location0" value="1439">
              </div>
              <div class="ui-radio">
                 <label for="location1" class="ui-btn ui-corner-all ui-btn-inherit ui-btn-icon-left ui-radio-off ui-last-child">1440</label>
                 <input type="radio" name="location" id="location1" value="1440">
              </div>
           </div>
        </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-12-05
          • 2015-10-01
          • 2016-12-06
          • 2017-06-21
          • 2011-09-25
          • 2011-09-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多