我正在尝试创建一个简单的脚本,该脚本将向按钮添加一个侦听器,以触发一个函数,该函数在页面完全加载时显示警报。
该脚本将在Chrome扩展中实现
我使用了以下代码:
document.addEventListener('DOMContentLoaded', function () {
showalert();
document.querySelector('button').addEventListener('click', showalert());
});
function showalert() {
alert("you just pressed the button");
}和我的HTML
<button id="button">button</button>侦听器永远不会添加到按钮中,也不会触发第一个showalert();。
我可能在这里做的很愚蠢,但我不明白为什么这不起作用。任何帮助都将不胜感激!
JSfiddle:http://jsfiddle.net/bunker1/fcrwt/1/
发布于 2013-03-16 21:35:43
发现了错误,我真的是太愚蠢了。
在将JSfiddle放在无包装上并从第二个参数中删除()之后,代码就可以工作了。
正确的代码:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', showalert, false);
}, false);
function showalert() {
alert("you just pressed the button");
}https://stackoverflow.com/questions/15449424
复制相似问题