我有这个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');
}
});
但是,都失败了,什么是合适的方法?谢谢!
最佳答案
这应该可行,您需要使用目标的值,该示例与您的代码很接近
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/