运行程序时出现此错误。我输入名称并单击登录按钮,页面将被定向到新页面,即 index.html 文件,我收到错误 Uncaught TypeError: Cannot read property 'addEventListener' of null in my first JS file。
这是我的第一个 JS 文件:
var name = '';
const login = document.querySelector('.logButton');
login.addEventListener('click', () =>{
name = document.querySelector('.name').value;
});
这是这个 JS 文件的 HTML 文件主体
<div class = loginPage>
<input type = 'text' placeholder= 'Username' class = names></input> <a href = '../index.html'><button class = logButton> Login</button></a>
</div>
这里是 index.html 的第二个 JS 文件
const now = new Date();
const hour = now.getHours();
const morning = " ";
const night = " ";
const div = document.querySelector('.page_1_body');
function print(docu){
div.innerHTML = "<h1> <a href = 'Page_2/page2.html'>" + docu +"</a>";
}
function dayrnight(name){
if ( hour <= 24 && hour < 18 ){
const morning = "<h1> Good Day " + name + " !</h1>";
print(morning);
} else {
const night = "<h1>Good evening " + name + " !</h1>";
print(night);
}
}
dayrnight(name);
这里是index.html文件
<body>
<div class = page_1_body>
</div>
<script src="index.js"></script>
<script src = "Login_page/Login.js"></script>
</body>
我发布了代码,这样它可以帮助解决我的问题。谢谢!
最佳答案
您错过了将 logButton
class
括在引号中。像这样修复它:
<button class = "logButton">
此外,您还需要确保当您尝试加载按钮
时已经生成了HTML,所以包装
document.onreadystatechange = function() {
//Your code here
}
围绕您的 JS 代码。
关于javascript - 未捕获的类型错误 : Cannot read property 'addEventListener' of null on javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50527587/