Html 简单的事件侦听器不起作用 - JS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17717175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:16:35  来源:igfitidea点击:

Simple event listener not working - JS

javascripthtmldomaddeventlistener

提问by user2594377

I have written an increbily simple event listener and yet it comes up with the error: Uncaught TypeError: Cannot call method 'addEventListener' of nullwhich suggests it is to do with the id maybe (also it works with document?

我写了一个非常简单的事件侦听器,但它出现了错误:Uncaught TypeError: Cannot call method 'addEventListener' of null这表明它可能与 id 有关(它也适用于document?

<html>
<head>
    <script type="text/javascript">
        function message () {
        alert("Hello!");
        }
        var button = document.getElementById('button');
        button.addEventListener('click', message, true);
    </script>
</head>
<body>
    <input type="button" id="button" value="Click me!" />
</body>
</html>

(I know I'm going to feel stupid after this, but I am a JS noob)

(我知道在这之后我会觉得自己很愚蠢,但我是一个 JS 菜鸟)

回答by Plato

at the time your script executes, the DOM has not been created. you can place your script after the body tags to run it after reading the html - but the better way to do it is by listening for DOMContentLoaded.

在您的脚本执行时,DOM 尚未创建。您可以将脚本放在 body 标签之后,以便在阅读 html 后运行它 - 但更好的方法是通过侦听DOMContentLoaded.

document.addEventListener('DOMContentLoaded', init, false);
function init(){
  function message () {
    alert("Hello!");
  }
  var button = document.getElementById('button');
  button.addEventListener('click', message, true);
};

window.onload = initworks too. I don't like it because it looks to me like one script could overwrite window.onload to be its own init function. (i haven't confirmed that happens or not)

window.onload = init也有效。我不喜欢它,因为它在我看来就像一个脚本可以覆盖 window.onload 成为它自己的 init 函数。(我还没有确认发生与否)

回答by user1882981

Because this script is executed when body isn't loaded yet. Use onload event, and within it paste your code.

因为这个脚本是在 body 还没有加载的时候执行的。使用 onload 事件,并在其中粘贴您的代码。