jquery设置单选框选中
使用 jQuery 设置单选框选中状态
在 jQuery 中,可以通过操作 DOM 元素的属性和方法来设置单选框(radio button)的选中状态。以下是几种常见的方法:
通过 prop() 方法设置选中状态
使用 prop() 方法可以设置单选框的 checked 属性为 true 或 false。这是推荐的方式,因为它直接操作 DOM 属性。

// 设置单选框选中
$('#radioButtonId').prop('checked', true);
// 取消选中单选框
$('#radioButtonId').prop('checked', false);
通过 attr() 方法设置选中状态
attr() 方法也可以用来设置单选框的选中状态,但它在 jQuery 1.6 之后被 prop() 方法取代,因为 prop() 更直接地操作 DOM 属性。

// 设置单选框选中
$('#radioButtonId').attr('checked', 'checked');
// 取消选中单选框
$('#radioButtonId').removeAttr('checked');
通过 name 属性选中单选框
如果需要通过单选框的 name 属性来选中某个选项,可以使用以下方式:
// 选中 name 为 "gender" 且 value 为 "male" 的单选框
$('input[name="gender"][value="male"]').prop('checked', true);
动态选中单选框
在动态场景中,例如根据用户输入或其他条件选中单选框,可以结合条件判断来实现:
var selectedValue = 'female';
$('input[name="gender"]').each(function() {
if ($(this).val() === selectedValue) {
$(this).prop('checked', true);
}
});
注意事项
- 使用
prop()方法比attr()方法更高效,尤其是在处理布尔属性(如checked、disabled等)时。 - 确保单选框的
name属性相同,以实现单选效果。 - 在表单提交或数据绑定时,只有被选中的单选框的值会被提交。
以上方法可以灵活应用于各种场景,根据实际需求选择合适的方式。






