JavaScript 监听 Radio 按钮点击事件 - 按 Name 属性分组
在 HTML 中,radio 元素可以通过 name 属性进行分组。因此,我们可以通过监听特定 name 的 radio 元素的点击事件来实现相应的操作。
例如,我们有如下 HTML 代码:
<input type='radio' name='gender' value='male'> Male<br>
<input type='radio' name='gender' value='female'> Female<br>
我们可以通过 JavaScript 代码监听 name 为 'gender' 的 radio 元素的点击事件:
document.querySelectorAll('input[name='gender']').forEach(function(radio) {
radio.addEventListener('click', function() {
console.log('选中了' + radio.value);
});
});
上述代码使用了 querySelectorAll 方法选择所有 name 为 'gender' 的 radio 元素,并对它们进行遍历添加点击事件监听器。当用户点击其中一个 radio 元素时,相应的回调函数将被调用,输出选中的值。
原文地址: https://www.cveoy.top/t/topic/opKX 著作权归作者所有。请勿转载和采集!