最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener DOMContentLoaded not working - Stack Overflow

programmeradmin6浏览0评论

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

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

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

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

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

JSfiddle: /

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

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

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

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

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/bunker1/fcrwt/1/

Share Improve this question edited Mar 16, 2013 at 13:11 Bunker asked Mar 16, 2013 at 12:44 BunkerBunker 1,0513 gold badges14 silver badges26 bronze badges 2
  • 1 addEventListener takes 3 args – stark Commented Mar 16, 2013 at 13:12
  • Thanks for the input, added the false argument in the fiddle without any luck unfortunately :( – Bunker Commented Mar 16, 2013 at 13:20
Add a ment  | 

1 Answer 1

Reset to default 4

Found the error, I was being stupid indeed.

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

correct code:

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

    function showalert() {
        alert("you just pressed the button");
    }
发布评论

评论列表(0)

  1. 暂无评论