我已经将此代码输入到 jfiddle 和这篇文章中,它运行良好,非常简单,点击图片就会改变。但是,当放入 Visual Studio 代码 (VSC) 时,我从控制台收到此代码错误,单击时图片不会更改:
“script.js:5 未捕获的类型错误:无法在 script.js:5 处读取 null 的属性 'addEventListener'”
我认为这可能是我需要的 VSC 扩展的问题?链接问题?
这是我的代码:
const main = document.getElementById("main")
const bill = document.getElementById("bill")
const nick = document.getElementById("nick")
main.addEventListener("click", () => {
bill.classList.toggle("hide")
nick.classList.toggle("hide")
})
* {
font-family: Sans-serif;
}
nav {
padding: 10px;
background-color: tomato;
}
ul {
list-style-type: none;
display: flex;
justify-content: space-around;
}
header {
border: 2px solid black;
text-align: center;
}
img {
border: 10px solid black;
border-radius: 20px;
display: block;
margin: 10px auto;
}
.hide {
display: none;
}
<html>
<head>
<link rel="stylesheet" href="style/style.css">
<script src="js/script.js"></script>
</head>
<body>
</body>
<nav>
<ul>
<li>Home</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
</nav>
<header>
<h1>Screen Legends</h1>
<p>A website dedicated to the legends of the silver screen</p>
</header>
<main id="main">
<img src="https://www.fillmurray.com/200/300" alt="bill murray" id="bill">
<img src="https://www.placecage.com/200/300" alt="nick cage" class="hide"id="nick">
</main>
</html>
谢谢,
杰克