javascript - 未捕获的类型错误 : Cannot read property 'addEventListener' of null on javascript

标签 javascript html

运行程序时出现此错误。我输入名称并单击登录按钮,页面将被定向到新页面,即 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>

我发布了代码,这样它可以帮助解决我的问题。谢谢!

最佳答案

您错过了将 logBu​​tton 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/

相关文章:

html - JSP文件上传

javascript - 悬停时一个接一个地显示子菜单

javascript - HTML/jQuery detach() 然后 insertAfter() 元素

javascript - 安装 Angular cli 时出错

javascript - 使用滚动折叠一个 div 直到某个点

jquery - "rel"的多个 Fancybox 2 画廊问题

javascript - undefined === undefined 比较什么?

javascript - 如何信任在互联网上找到的 javascript 开源库

javascript - 在 html5 音频标签中播放音频时出现 [object MediaError]

javascript - 包含标记为无效的转义单引号的 JSON 字符串