admin管理员组文章数量:1418410
I'm writing a Tampermonkey script that adds a button to a page and then adds an onClick event to that button. I have the button on the page where I want it, but when I try to attach a click event using "addEventListener" as remended in related questions about click events in user scripts, the event handler fires on page load and not when the button clicks.
var testbutton = document.createElement("button");
testbutton.addEventListener('click', alert("Working"), false);
testbutton.id = "testbutton";
testbutton.innerHTML = "This is a button";
testElement.appendChild(testbutton);
Basically, when the page loads the "Working" alert fires, but then not when I click the button. I get no console feedback either. What am I missing?
I'm writing a Tampermonkey script that adds a button to a page and then adds an onClick event to that button. I have the button on the page where I want it, but when I try to attach a click event using "addEventListener" as remended in related questions about click events in user scripts, the event handler fires on page load and not when the button clicks.
var testbutton = document.createElement("button");
testbutton.addEventListener('click', alert("Working"), false);
testbutton.id = "testbutton";
testbutton.innerHTML = "This is a button";
testElement.appendChild(testbutton);
Basically, when the page loads the "Working" alert fires, but then not when I click the button. I get no console feedback either. What am I missing?
Share Improve this question asked Mar 30, 2015 at 14:11 EseirtEseirt 2613 silver badges11 bronze badges 01 Answer
Reset to default 6That's because you're calling alert on pageload, not on click, you probably wanted an anonymous function as well
var testbutton = document.createElement("button");
testbutton.addEventListener('click', function() {
alert("Working");
}, false);
testbutton.id = "testbutton";
testbutton.innerHTML = "This is a button";
testElement.appendChild(testbutton);
Whenever you add the parentheses to a function, it's called immediately, to call the function on an event, you just want to reference it, here are some examples
addEventListener('click', alert("Working"), false); // called immediately
addEventListener('click', alert, false); // called on click
addEventListener('click', function() {}, false); // called on click
addEventListener('click', function() {
alert();
}, false); // called on click
本文标签: javascriptClick event fires on document load TampermonkeyStack Overflow
版权声明:本文标题:javascript - Click event fires on document load Tampermonkey - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745275187a2651141.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论