我有一组单选按钮,我想使用 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>
我做错了什么?
最佳答案
由于单选按钮是 #radios
div 的子级,因此您需要使用 $.fn.find()
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
代码,同时将更改事件与单选按钮绑定(bind)
$( "#radios input:radio" ).on( "change", function() {
myID = $("#radios").find(":radio:checked").first().attr('id');
alert(myID);
});
注意:您还可以使用 $.fn.children()
,但是 .children()
方法与 .find()
不同。
关于javascript - 使用 Jquery 更改检查单选按钮 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30165324/