javascript addEventListener DOMContentLoaded 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15449424/
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-10-27 00:48:03  来源:igfitidea点击:

addEventListener DOMContentLoaded not working

javascriptgoogle-chrome-extension

提问by Bunker

I'm trying to create a simple script that will add a listener to a button to trigger a function that displays an alert when the page is fully loaded.

我正在尝试创建一个简单的脚本,它将向按钮添加一个侦听器,以触发一个在页面完全加载时显示警报的函数。

The script is to be implemented in a Chrome Extension

该脚本将在 Chrome 扩展程序中实现

I'm using the following code:

我正在使用以下代码:

    document.addEventListener('DOMContentLoaded', function () {
        showalert();
        document.querySelector('button').addEventListener('click', showalert());
    });

    function showalert() {
        alert("you just pressed the button");
    }

And my HTML

还有我的 HTML

    <button id="button">button</button>

The listener is never added to the button, also the first showalert(); is not fired.

监听器永远不会添加到按钮上,也是第一个 showalert(); 没有被解雇。

I'm probably being stupid here, but I'm failing to see why this is not working. Any help would be greatly appreciated!

我可能在这里很愚蠢,但我不明白为什么这不起作用。任何帮助将不胜感激!

JSfiddle: http://jsfiddle.net/bunker1/fcrwt/1/

JSfiddle:http: //jsfiddle.net/bunker1/fcrwt/1/

回答by Bunker

Found the error, I was being stupid indeed.

发现错误,我确实是愚蠢的。

The code worked after putting JSfiddle on no wrap and removing the () from the second arg.

在将 JSfiddle 放在不换行并从第二个 arg 中删除 () 后,代码工作。

correct code:

正确的代码:

    document.addEventListener('DOMContentLoaded', function () {
         document.querySelector('button').addEventListener('click', showalert, false);
    }, false);

    function showalert() {
        alert("you just pressed the button");
    }