javascript - 使用 Jquery 更改检查单选按钮 ID

标签 javascript jquery html dom

我有一组单选按钮,我想使用 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/

相关文章:

javascript - 如何将 JavaScript 转换为 Ruby?

javascript - 如何在 HTML 中做列表到网格的动画过渡?

html - SASS -scss 背景图像链接

jquery - 使用 window.resize 在图像上再次运行加载函数?

jquery - Chrome 中可调整大小的 Div 在缩放时导致内容偏移

javascript - Bootstrap 多选动态选择动态添加的字段不起作用

javascript - Backbone.js - 如何将集合保存到 localStorage?

javascript - 将值从 View 模型传递到 zk 中的脚本

javascript - $.getJSON 结果转为 html

javascript - 无法从不同的脚本文件读取返回的 Javascript 对象