我有两个页面,page1.html
和 page2.html
,它们链接到同一个 javascript 文件。
这是第 1 页的标记
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button class="button">HIT ME</button>
<div class="trig"></div>
</body>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</html>
和第 2 页
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button class="button_2">HIT ME</button>
</body>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</html>
这是脚本
document.querySelector(".button").onclick = function(){
document.querySelector(".trig").style.display = "block";
}
当我刷新第 2 页时,我得到
Uncaught TypeError: Cannot set property 'onclick' of null error
显然是因为它找不到.button
类
但是当我在 jquery 中编写相同的内容时,它可以正常运行,两个页面都没有错误。
$('.button').click(function(){
$('.trig').show();
});
我想了解为什么会发生这种情况以及如何在 vanilla js 中编写相同的内容而不出现任何错误。
最佳答案
I want to understand why this happens and how to write the same thing in vanilla js without getting any errors.
因为当button
类的元素不存在时,$('.button')
不会返回null,而document.querySelector (“.button”)
确实如此。
您需要首先使用 vanila js api 检查 null
var button = document.querySelector(".button");
button && ( button.onclick = function(){
document.querySelector(".trig").style.display = "block";
});
关于javascript - 未捕获的类型错误 : Cannot set property 'onclick' of null error on vanilla js but not in jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46485798/