如何在输入框有内容时修改标签颜色?多页面JS报错求助
问题:跨页面复用JS代码时注册页功能失效
我把同一段JavaScript代码引入多个页面,想要实现输入框有内容时修改对应表单标签颜色的功能,该功能在登录页面正常运行,但在SignUp.html页面报错无法生效。以下是我的代码:
// LOGIN INPUT VARIABLES let usernameInput = document.querySelector("#usernameInput"); let passwordInput = document.querySelector("#passwordInput"); // SIGN UP INPUT VARIABLES let firstNameInput = document.querySelector("#firstNameInput"); let lastNameInput = document.querySelector("#lastNameInput"); usernameInput.addEventListener("input", function() { document.querySelector("#usernameLabel").style.color = "#98589e"; if (usernameInput.value == '') { document.querySelector("#usernameLabel").style.color = "#b9c0c8"; } }); passwordInput.addEventListener("input", function() { document.querySelector("#passwordLabel").style.color = "#98589e"; if (passwordInput.value == '') { document.querySelector("#passwordLabel").style.color = "#b9c0c8"; } }); firstNameInput.addEventListener("input", function() { document.querySelector("#firstNameLabel").style.color = "#98589e"; if (firstNameInput.value == '') { document.querySelector("#firstNameLabel").style.color = "#b9c0c8"; } }); lastNameInput.addEventListener("input", function() { document.querySelector("#lastNameLabel").style.color = "#98589e"; if (lastNameInput.value == '') { document.querySelector("#lastNameLabel").style.color = "#b9c0c8"; } });
问题原因&解决方案
为什么会报错?
很简单——SignUp页面里根本没有登录页的#usernameInput和#passwordInput元素啊!当代码在注册页执行时,document.querySelector找不到这些元素,会返回null,接着你尝试给null调用addEventListener,直接就触发了JS错误,后面处理注册输入框的代码也被中断,自然没法生效了。
修复后的代码
我们可以先检查元素是否存在再绑定事件,同时把重复的逻辑抽成通用函数,让代码更简洁健壮:
// 通用工具函数:统一处理输入框与标签的颜色切换逻辑 function bindInputLabelToggle(inputSelector, labelSelector) { // 先获取元素,不存在就直接返回,避免报错 const inputElement = document.querySelector(inputSelector); const labelElement = document.querySelector(labelSelector); if (!inputElement || !labelElement) return; inputElement.addEventListener("input", function() { // 用三元表达式简化判断逻辑,同时处理空空格的情况 labelElement.style.color = this.value.trim() !== "" ? "#98589e" : "#b9c0c8"; }); } // 分别绑定各页面的输入框与标签 bindInputLabelToggle("#usernameInput", "#usernameLabel"); bindInputLabelToggle("#passwordInput", "#passwordLabel"); bindInputLabelToggle("#firstNameInput", "#firstNameLabel"); bindInputLabelToggle("#lastNameInput", "#lastNameLabel");
修复效果
现在不管是登录页还是注册页,代码都会自动跳过当前页面不存在的元素,只有找到对应输入框和标签时才会绑定事件,再也不会因为元素不存在抛出错误,两个页面的功能都能正常运行啦。
内容的提问来源于stack exchange,提问作者EricGFig
相关产品推荐
相关产品推荐

