最稳妥方式是document.querySelector('input[name="gender"]:checked')?.value || '',必须加:checked伪类,否则返回首个元素;若无选中项则返回null,需空值处理。

用 document.querySelector() 直接获取选中项的 value
最常用也最稳妥的方式是通过 name 属性定位整组 radio,再找其中被选中的那个。注意:必须加 :checked 伪类,否则返回的是第一个元素(不管是否选中)。
- 如果没选中任何一项,
document.querySelector('input[name="gender"]:checked')返回null,直接取.value会报Cannot read property 'value' of null - 推荐写法:
const selected = document.querySelector('input[name="gender"]:checked'); const value = selected ? selected.value : ''; - 不要用
getElementsByTagName('input')遍历判断 —— 性能差、易漏掉动态插入的元素
用 document.querySelectorAll() 配合 Array.prototype.find()
适合需要额外逻辑判断的场景,比如根据 value 做映射、或需兼容老浏览器(但此时得用 for 循环代替 find)。
-
const radios = document.querySelectorAll('input[name="plan"]');返回的是NodeList,不是数组,不能直接调.find(),得先转:Array.from(radios).find(el => el.checked) - IE11 不支持
Array.from,若需兼容,改用for (let i = 0; i - 这种写法比
querySelector多一次遍历,无必要时不建议
监听 change 事件时,this.value 就是当前选中值
给单个 radio 绑定事件没意义,应该绑定在父容器或用事件委托——但更简单的是直接绑在任意一个 radio 上,靠 this 拿值。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
- 错误写法:
document.querySelectorAll('input[name="mode"]').forEach(el => el.addEventListener('change', e => console.log(e.target.value)))—— 每次都触发,冗余 - 正确做法:只绑定一次,例如
document.querySelector('input[name="mode"]').parentElement.addEventListener('change', e => { if (e.target.type === 'radio') console.log(e.target.value); }) - 注意:radio 的
change只在选项切换时触发,点击已选中的项不会再次触发
表单提交前校验:别忘了 radio 默认没有 required 也能提交空值
HTML5 的 required 对 radio 有效,但仅当整组中**至少一个有该属性**且**无默认选中项**时,才阻止提交并提示。很多人误以为加一个 required 就够了。
- 必须写成:
,且同一name下其他 radio **不加**required,否则多个 required 会互相干扰 - 更可靠的做法是 JS 校验:
if (!document.querySelector('input[name="level"]:checked')) { alert('请选择等级'); return false; } - 服务端永远要二次校验 —— 前端校验可被绕过
实际开发中最容易卡住的,是忘记检查 querySelector 返回 null 的情况,以及混淆 change 和 click 事件的触发时机。这两处出错,调试起来往往要花比写代码更久的时间。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










