我有这个HTML:

 <p class="form-row " id="radio_xsdfYxsfWEx_field">
           <label>Radio</label>
           <label for="radio_xsdfYxsfWEx_Male" class="radio">
                <input type="radio" class="input-radio um-field" value="Male" name="radio_xsdfYxsfWEx" id="radio_xsdfYxsfWEx_Male">Male</label>
           <label for="radio_xsdfYxsfWEx_Female" class="radio">
                <input type="radio" class="input-radio um-field" value="Female" name="radio_xsdfYxsfWEx" id="radio_xsdfYxsfWEx_Female">Female</label>
    </p>


我需要知道选择的值是男性还是女性。我可以这样做,但像这样,但ID不同

    jQuery("#radio_xsdfYxsfWEx_field").on('change', function(){
       var value = this.value;
       if( value === 'Female' ) {
        alert('succcess');
     }
   });


如果我可以通过名称获取值,它将更简单:

jQuery("radio_xsdfYxsfWEx").on('change', function(){
       var value = this.value;
       if( value === 'Female' ) {
        alert('succcess');
     }
   });


但是,两者都失败了,什么方法合适?谢谢!

最佳答案

那应该起作用,您需要使用target的值,该示例接近您的代码


jQuery("#radio_xsdfYxsfWEx_field").on('change', function(e){
       if( e.target.value === 'Female' ) {
        alert('succcess');
     }
   });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="form-row " id="radio_xsdfYxsfWEx_field">
           <label>Radio</label>
           <label for="radio_xsdfYxsfWEx_Male" class="radio">
                <input type="radio" class="input-radio um-field" value="Male" name="radio_xsdfYxsfWEx" id="radio_xsdfYxsfWEx_Male">Male</label>
           <label for="radio_xsdfYxsfWEx_Female" class="radio">
                <input type="radio" class="input-radio um-field" value="Female" name="radio_xsdfYxsfWEx" id="radio_xsdfYxsfWEx_Female">Female</label>
    </p>

关于javascript - 我怎么知道选择哪个值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49476242/

10-09 14:50