Javascript 未捕获的类型错误无法读取 属性 的 null。错误是由不同的 HTML 页面引起的?

Javascript uncaught type error cant read property of null. Error is being caused by a different HTML page?

所以我在一个网站上工作,并决定使用 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>

您应该首先使用 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');