简体   繁体   English

单击事件在文档加载Tampermonkey时触发

[英]Click event fires on document load Tampermonkey

I'm writing a Tampermonkey script that adds a button to a page and then adds an onClick event to that button. 我正在编写一个Tampermonkey脚本,该脚本将一个按钮添加到页面,然后将onClick事件添加到该按钮。 I have the button on the page where I want it, but when I try to attach a click event using "addEventListener" as recommended in related questions about click events in user scripts, the event handler fires on page load and not when the button clicks. 我在页面上有我想要的按钮,但是当我尝试按照有关用户脚本中的点击事件的相关问题中的建议使用“ addEventListener”附加点击事件时,事件处理程序将在页面加载时触发,而不是在按钮点击时触发。

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? 我想念什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM