当我将我的 Javascript 链接到多个页面时,我很困惑为什么会出现此错误。我正在尝试使用 Javascript 在输入字段包含文本时立即更改表单标签的颜色。它在“登录”部分工作正常,但在我将它链接到 SignUp.html 文件时不起作用并给我一个错误。这是我在 codepen 上的元素的链接,如果你不想看我正在谈论的内容的话。如果有任何帮助,我将不胜感激!
// 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";
}
});
最佳答案
你的错误是
Uncaught TypeError: Cannot read property 'addEventListener' of null
它指向第 8 行。实际上,在您的 signUp.html
文件中,您没有名为 #usernameInput
的元素(实际上也没有 #passwordInput
) .
所以 usernameInput
和 passwordInput
在 signUp.html
中加载此文件时都是未定义的(它们仅在 中加载时定义>登录.html
)
因此,您不应该为这两个页面使用相同的 JavaScript 文件。
对于 signUp.html
页面,您应该只有以下 JavaScript 代码:
let firstNameInput = document.querySelector("#firstNameInput");
let lastNameInput = document.querySelector("#lastNameInput");
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";
}
});
如果您真的想保留单个 JavaScript 文件,请考虑使用函数来分隔您的代码。例如,有一个用于登录样式处理的函数和另一个用于注册样式处理的函数。
关于javascript - 输入字段收到文本时如何更改标签颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50537838/