[英]addEventListener + setTimeout
It's the first time I encounter such an issue with the addEventListener() method. 这是我第一次使用addEventListener()方法遇到这样的问题。 When I try to use it with a setTimeout, the function is automatically called, even though the addEventListener has a "click" property. 当我尝试将其与setTimeout一起使用时,即使addEventListener具有“ click”属性,也会自动调用该函数。
<button id="test">Test</button>
document.getElementById("test").addEventListener("click", setTimeout(myFunc, 2000));
function myFunc() {
console.log("Hello");
}
This would be what you want. 这就是您想要的。
document.getElementById("test").addEventListener("click", function(){setTimeout(myFunc, 2000)}); function myFunc() { console.log("Hello"); }
<button id="test">Test</button>
You could keep the exact same code you have now but curry
your function via bind
vs. trying to invoke it while also trying to pass it as an argument. 你可以让你现在有完全相同的代码,但curry
通过你的函数bind
与尝试调用它,同时也试图把它作为参数传递。
document.getElementById("test").addEventListener("click", setTimeout.bind(null, myFunc, 2000)); function myFunc() { console.log("Hello"); }
<button id="test">Click</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.