我有一组单选按钮,我想用jQuery找到所选的单选按钮ID。
这是我的一组单选按钮,带有以下jQueryCode --每当我更改单选按钮时,我都会收到一个“未定义的”警报。
$("#radios").on("change", function() {
myID = $("#radios").nextAll(":radio:checked").first().attr('id');
alert(myID);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="radios">
<input id="option1" name="options" type="radio" checked>
<label value="test" for="option1">X-01</label>
<input id="option2" name="options" type="radio">
<label for="option2">X-02</label>
<input id="option3" name="options" type="radio">
<label for="option3">X-03</label>
<input id="option4" name="options" type="radio">
<label for="option4">M-01</label>
<input id="option5" name="options" type="radio">
<label for="option5">M-02</label>
<input id="option6" name="options" type="radio">
<label for="option6">M-04</label>
<input id="option7" name="options" type="radio">
<label for="option7">L-01</label>
<input id="option8" name="options" type="radio">
<label for="option8">L-02</label>
</div>
我做错了什么?
发布于 2015-05-11 10:29:44
由于单选按钮是#radios div的子程序,所以需要使用$.fn.find()。
获取由选择器、jQuery对象或元素筛选的当前匹配元素集中的每个元素的子元素。
代码,也可以用单选按钮绑定更改事件。
$( "#radios input:radio" ).on( "change", function() {
myID = $("#radios").find(":radio:checked").first().attr('id');
alert(myID);
});注意:您也可以使用$.fn.children(),但是.children()方法不同于.find()。
发布于 2015-05-11 10:30:46
您需要使用find方法来获得radio。
$("#radios").on("change", function () {
myID = $("#radios").find(":radio:checked").first().attr('id');
// ^^^^
alert(myID);
});演示:http://fiddle.jshell.net/575Lycoj/
发布于 2015-05-11 10:30:50
你需要
1)将更改事件附加到输入元素,而不是使用id #radios附加到div
2)然后在其中找到检查元素。:
$( "#radios input" ).on( "change", function() {
myID = $("#radios :radio:checked").first().attr('id');
alert(myID);
});https://stackoverflow.com/questions/30165324
复制相似问题