我尝试用jQuery检查单选按钮。这是我的代码:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

JavaScript:

jQuery("#radio_1").attr('checked', true);

不工作:

jQuery("input[value='1']").attr('checked', true);

不工作:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

不工作:

你还有别的主意吗?我错过了什么?


当前回答

得到的值:

$("[name='type'][checked]").attr("value");

设置的值:

$(this).attr({"checked":true}).prop({"checked":true});

单选按钮单击add attr checked:

$("[name='type']").click(function(){
  $("[name='type']").removeAttr("checked");
  $(this).attr({"checked":true}).prop({"checked":true});
});

其他回答

短而易读的选项:

$("#radio_1").is(":checked")

它返回true或false,所以你可以在if语句中使用它。

我也遇到过类似的问题,一个简单的解决方法就是:

.click()

如果在调用函数后刷新radio,则任何其他解决方案都将工作。

如果你不想为这么简单的事情包含一个像jQuery这样的大库,这里有一个使用内置DOM方法的替代解决方案:

// Check checkbox by id: document.querySelector('#radio_1').checked = true; // Check checkbox by value: document.querySelector('#type > [value="1"]').checked = true; // If this is the only input with a value of 1 on the page, you can leave out the #type > document.querySelector('[value="1"]').checked = true; <form> <div id='type'> <input type='radio' id='radio_1' name='type' value='1' /> <input type='radio' id='radio_2' name='type' value='2' /> <input type='radio' id='radio_3' name='type' value='3' /> </div> </form>

jQuery 1.6中添加了另一个函数prop(),用于相同的目的。

$("#radio_1").prop("checked", true); 

是的,这对我来说很管用:

$("#radio_1").attr('checked', 'checked');