我尝试用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);

不工作:

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


当前回答

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

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

其他回答

如果你不想为这么简单的事情包含一个像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>

我们应该告诉它是单选按钮。所以请尝试以下代码。

$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);

最短的

radio_1.checked

checkBtn。Onclick = e=> { console.log (radio_1。检查); } 选择第一个单选并单击按钮 <!——问题html——> < >形式 < div id =“类型”> <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 > > < /形式 <!——测试html——> <按钮id = " checkBtn " >查看> < /按钮

这里是Jsfiddle代码片段

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

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

Attr接受两个字符串。

正确的做法是:

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