admin管理员组文章数量:1323023
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
1 Answer
Reset to default 4Found 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");
}
本文标签: javascriptaddEventListener DOMContentLoaded not workingStack Overflow
版权声明:本文标题:javascript - addEventListener DOMContentLoaded not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742111661a2421285.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论