表单元素上的onClick事件仅触发一次问题求助
解决点击事件仅触发一次的无障碍表单问题
我正在尝试创建一个可切换无障碍功能的表单,但onClick事件仅能触发一次,不清楚其中原因。
原代码
JavaScript
function updateAccessible() { if (document.getElementById("font").value === true) { console.log("update true") document.querySelector(':root').style.setProperty('--font', 'cursive, sans-serif') } else { console.log("update false") document.querySelector(':root').style.setProperty('--font', 'sans-serif') } document.getElementById("accessibleForm").addEventListener("click", updateAccessible) }
CSS
:root { --font: cursive, sans-serif; } * { font-family: var(--font) }
HTML
<form onclick="updateAccessible()" id="accesibleForm"> <input type="checkbox" name="font" id="font" checked><label for="font">Use custom font</label> </form> <p>Example Text</p>
问题分析
- 元素ID拼写不匹配:HTML里表单ID是
accesibleForm(少一个s),但JS里用getElementById("accessibleForm")查找,导致无法定位元素,后续事件绑定代码无效。 - Checkbox状态判断错误:复选框的选中状态不能用
value === true判断,value默认值为"on",与选中状态无关,正确判断方式是使用checked属性。 - 重复绑定事件:函数内部再次调用
addEventListener绑定点击事件,属于多余操作,还可能引发后续触发异常。
修正后的代码
JavaScript
function updateAccessible() { const fontCheckbox = document.getElementById("font"); if (fontCheckbox.checked) { console.log("启用自定义字体"); document.querySelector(':root').style.setProperty('--font', 'cursive, sans-serif'); } else { console.log("禁用自定义字体"); document.querySelector(':root').style.setProperty('--font', 'sans-serif'); } }
HTML(修正ID拼写)
<form onclick="updateAccessible()" id="accessibleForm"> <input type="checkbox" name="font" id="font" checked><label for="font">Use custom font</label> </form> <p>Example Text</p>
修正说明
- 移除函数内部的
addEventListener,已通过HTML的onclick绑定函数,无需重复绑定。 - 修正表单ID拼写,确保JS能正确定位元素。
- 改用
checked属性判断复选框状态,逻辑准确。 - 调整日志文本,让调试信息更清晰直观。
内容的提问来源于stack exchange,提问作者Afterlifepro
相关产品推荐
相关产品推荐

