Javascript 未捕获的 typeerror 无法读取 null 属性。错误是由其他 HTML 页面引起的吗?
2022-04-23
81
因此,我正在开发一个网站,并决定使用 5 个不同的 html 页面,而我实际上并不这么做。我使用的是 javascript 文件,我认为当我继续访问 contact.html 时,JS 无法找到 index.html 中的元素,这是有道理的。但我该如何解决这个问题?
script.js
//code i'd like to run in index.html
let highlighter = (selected, ignored1, ignored2) => {
document.getElementById(selected).addEventListener("click", ()=> {
let highlighted = document.getElementById(selected).style.backgroundColor = "#ECECEC";
let ignored = [ignored1,ignored2];
for (let i = 0; i < ignored.length; i++) {
document.getElementById(ignored[i]).style.backgroundColor = "#FFFFFF"
}
});
}
highlighter("alpha", "beta", "charlie");
highlighter("beta", "alpha", "charlie");
highlighter("charlie", "alpha", "beta");
//code i'd like to run in contact.html
document.getElementById("contact-us").addEventListener("click", ()=> {
alert("contact us test");
});
//code i'd like to have run everywhere
alert('test');
index.html
<html>
<body>
<h1 id="alpha">test</h1>
<h1 id="beta">test</h1>
<h1 id="charlie">test</h1>
</body>
</html>
contact.html
<html>
<body>
<div id="contact-us">
<h1>Click me!</h1>
</div>
</body>
</html>
1个回答
您应该首先使用 if 条件检查元素是否存在:
let highlighter = (selected, ignored1, ignored2) => {
if(!document.getElementById(selected)) {
return;
}
document.getElementById(selected).addEventListener("click", ()=> {
let highlighted = document.getElementById(selected).style.backgroundColor = "#ECECEC";
let ignored = [ignored1,ignored2];
for (let i = 0; i < ignored.length; i++) {
document.getElementById(ignored[i]).style.backgroundColor = "#FFFFFF"
}
});
}
highlighter("alpha", "beta", "charlie");
highlighter("beta", "alpha", "charlie");
highlighter("charlie", "alpha", "beta");
//code i'd like to run in contact.html
if(document.getElementById("contact-us") {
document.getElementById("contact-us").addEventListener("click", ()=> {
alert("contact us test");
});
}
//code i'd like to have run everywhere
alert('test');
Suraj Khanal
2022-04-23