双Checkbox文本颜色切换故障求助:仅左侧控件生效
问题原因与解决方案
核心问题
两个独立JS文件中重复使用了相同的const变量名greetingtex,由于脚本都运行在全局作用域下,重复声明const变量会触发语法错误,导致右侧Checkbox对应的JS代码无法执行,因此右侧功能失效。
修复方案
给两个变量设置不同的名称,避免全局作用域内的变量冲突:
修正后的左侧Checkbox JS(checkboxleft.js)
const leftcheckbox = document.getElementById("checkbox1"); const greetingTexLeft = document.getElementById("greetingL"); leftcheckbox.addEventListener("change", () => { if (leftcheckbox.checked) { greetingTexLeft.style.color = "Red"; } else { greetingTexLeft.style.color = ""; } });
修正后的右侧Checkbox JS(checkboxright.js)
const rightcheckbox = document.getElementById("checkbox2"); const greetingTexRight = document.getElementById("greetingR"); rightcheckbox.addEventListener("change", () => { if (rightcheckbox.checked) { greetingTexRight.style.color = "Red"; } else { greetingTexRight.style.color = ""; } });
额外优化建议
如果不想担心全局变量冲突,可以将每个脚本的代码包裹在立即执行函数表达式(IIFE)中,形成独立作用域:
左侧JS优化版
(function() { const leftcheckbox = document.getElementById("checkbox1"); const greetingtex = document.getElementById("greetingL"); leftcheckbox.addEventListener("change", () => { if (leftcheckbox.checked) { greetingtex.style.color = "Red"; } else { greetingtex.style.color = ""; } }); })();
右侧JS优化版
(function() { const rightcheckbox = document.getElementById("checkbox2"); const greetingtex = document.getElementById("greetingR"); rightcheckbox.addEventListener("change", () => { if (rightcheckbox.checked) { greetingtex.style.color = "Red"; } else { greetingtex.style.color = ""; } }); })();
内容的提问来源于stack exchange,提问作者Sovann Sun
相关产品推荐
相关产品推荐

