如何使用jQuery获取单选按钮的文本而不是值?

时间:2013-01-14 14:43:50

标签: jquery

这是软件生成的代码

<div id="cred_form_3584_1_wpcf-ticket-month-or-course-radios" class="myzebra-radios">
  <div class="myzebra-radios-single">
    <label class="myzebra-style-label">
      <input id="cred_form_3584_1_wpcf-ticket-month-or-course_wpcf-fields-radio-option-a6da15467aeb84f539c0dc1cd766ccd6-2" class="myzebra-control myzebra-radio myzebra-prime-name-wpcf-ticket-month-or-course" type="radio" checked="checked" value="wpcf-fields-radio-option-a6da15467aeb84f539c0dc1cd766ccd6-2" name="wpcf-ticket-month-or-course">
      <span class="myzebra-radio-replace"></span>
    </label>
    <label id="cred_form_3584_1_label_wpcf-ticket-month-or-course_wpcf-fields-radio-option-a6da15467aeb84f539c0dc1cd766ccd6-2" for="cred_form_3584_1_wpcf-ticket-month-or-course_wpcf-fields-radio-option-a6da15467aeb84f539c0dc1cd766ccd6-2">per month</label>
  </div>
<div class="myzebra-radios-single">
  <label class="myzebra-style-label">
    <input id="cred_form_3584_1_wpcf-ticket-month-or-course_wpcf-fields-radio-option-f63eb739e2a6499a882c8e82aa35b028-1" class="myzebra-control myzebra-radio myzebra-prime-name-wpcf-ticket-month-or-course" type="radio" value="wpcf-fields-radio-option-f63eb739e2a6499a882c8e82aa35b028-1" name="wpcf-ticket-month-or-course">
    <span class="myzebra-radio-replace"></span>
  </label>
  <label id="cred_form_3584_1_label_wpcf-ticket-month-or-course_wpcf-fields-radio-option-f63eb739e2a6499a882c8e82aa35b028-1" for="cred_form_3584_1_wpcf-ticket-month-or-course_wpcf-fields-radio-option-f63eb739e2a6499a882c8e82aa35b028-1">per course</label>
</div>

使用此代码:

alert($('input[@name="myzebra-radios-single"]:checked').text());

我得到的是值而不是文本。如何获取文本(例如每月)?

3 个答案:

答案 0 :(得分:3)

要获取label的内容,您需要使用其for=属性:

var $input = $('input[name=something]:checked');
var text = $('label[for='+$input.attr('id')+']').text();

http://jsfiddle.net/mblase75/RDPP7/

答案 1 :(得分:0)

首先,无线电元素没有任何文本值,如果他们这样做的话。

alert($('input[@name="myzebra-radios-single"]:checked').text());
// Should be
alert($('input[@name="wpcf-ticket-month-or-course"]:checked').text());

当我分解您的输入时,它们看起来像这样

<input 
    id="cred_form_3584_1_wpcf-ticket-month-or-course_wpcf-fields-radio-option-f63eb739e2a6499a882c8e82aa35b028-1" 
    class="myzebra-control myzebra-radio myzebra-prime-name-wpcf-ticket-month-or-course" 
    type="radio" 
    value="wpcf-fields-radio-option-f63eb739e2a6499a882c8e82aa35b028-1" 
    name="wpcf-ticket-month-or-course">

如果你想从上面选择某个属性,可以使用.val()。text()或.attr()。

答案 2 :(得分:0)

尝试:

alert($('input[@name="myzebra-radios-single"]:checked').attr('name'));