gpt4 book ai didi

javascript - 如何解决 TypeError : document. querySelector(...) 为空?

转载 作者:行者123 更新时间:2023-12-03 01:02:09 25 4
gpt4 key购买 nike

我尝试使用 document.querySelector() 定位图像,但它给我一个错误,提示 TypeError: document.querySelector(...) is null

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Step 1</title>
<style>
#image1{

}
</style>
<script>
document.querySelector('#image1').addEventListener("click",myFunction);
// addEventListener(event, function, useCapture)
function myFunction(){
alert("alert on click");
}
</script>
</head>
<body>
<img src="images/image1.jpg" id="image1" />
</body>
</html>

最佳答案

DOMContentLoaded

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

您的脚本在 DOM 准备好之前运行。您必须使用 DOMContentLoaded 包装代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Step 1</title>
<style>
#image1{

}
</style>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector('#image1').addEventListener("click",myFunction);
// addEventListener(event, function, useCapture)
function myFunction(){
alert("alert on click");
}
});
</script>
</head>
<body>
<img src="images/image1.jpg" id="image1" />
</body>
</html>

关于javascript - 如何解决 TypeError : document. querySelector(...) 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52577326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com