根据ID在jquery中设置单选按钮'checked'单选、按钮、根据、ID

2023-09-06 19:29:55 作者:窗台人影独坐

我有两个同名的单选按钮,默认选中一个.从 id 中选择时如何在 jQuery 中选中或取消选中单选按钮?

I have two radio buttons with the same name, one is checked by default. How can you check or uncheck a radio button in jQuery when selecting from id?

我试过了:

$('#radio1').attr('checked','checked');
$('#radio1').attr('checked', true);

似乎没有任何效果..有什么想法吗?

Nothing seems to work.. any ideas?

谢谢!

推荐答案

您不能多次拥有相同的 id (#radio1),请改用 class.

You can not have same id (#radio1) more than once, use a class instead.

$('.radio1').attr('checked', true);
$('.radio2').attr('checked', true);

id 应该在每个页面的每个元素中使用一次.

The id should be used once per element per page.

如果你想在 click 上勾选/取消勾选,你可以这样做:

If you want to check/uncheck on click however, you may do like:

$('#someid').click(function(){
  $('#radio1').attr('checked', true);
});

或者

$('#someid').click(function(){
  $('#radio1').attr('checked', this.checked);
});