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 0
Add a ment  | 

1 Answer 1

Reset to default 6

That'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