Javascript,addEventListener 回调函数立即执行且仅执行一次? [英] Javascript, addEventListener callback function executes immediately and only once?

查看:88
本文介绍了Javascript,addEventListener 回调函数立即执行且仅执行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 addEventListener 回调的 functionfunction() 之间的区别.在我尝试传递参数之前,这不是问题.基本上,

I've noticed a difference between function and function() for addEventListener's callback. Which isn't a problem till I tried passing a parameter. Basically,

element.addEventListener("hover", logInput, false );
function logInput(){
    console.log('registered!');
}

按预期工作,但添加括号会使其立即记录,而不会持续响应事件触发器:

works as intended, but adding parenthesis will cause it log immediately, without continual response to the event trigger:

element.addEventListener("hover", logInput(), false );
function logInput(){
    console.log('registered!');
}

这是为什么?以及如何在传递参数时使其工作,例如:

Why is this? And how can I get it to work while passing a parameter such as:

element.addEventListener("hover", logOnInput(this), false );
function logOnInput(triggeredElement){
    console.log(triggeredElement);
}

推荐答案

(如果你真的想要触发元素,不要传递任何东西.this 会自动设置为触发元素.)

(If you really want the triggered element, don't pass anything. this will automatically be set to the triggered element.)

element.addEventListener("hover", logOnInput, false);
function logOnInput(){
    console.log(this);
}

<小时>

要回答更一般的问题...

有几种方法可以将函数作为参数传递,并且已经设置了某些参数(这称为部分应用程序").如果您能够使用现代 JavaScript 功能,最简单的方法可能是使用 箭头功能.

There are a few ways to pass a function as an argument with certain arguments already set (this is referred to as "partial application"). If you are able to use modern JavaScript features, the simplest way is probably to use an arrow function.

element.addEventListener("hover", () => logOnInput(foo), false);
function logOnInput(message){
    console.log(message);
}

这只适用于非常现代的浏览器.它不起作用,例如在 IE 11 中.为了支持旧浏览器,您可以使用函数表达式的较长形式.

This will only work on very modern browsers. It won't work, for example, in IE 11. In order to support older browsers, you can use the longer form of a function expression.

element.addEventListener("hover", function() {logOnInput(foo);}, false);
function logOnInput(message){
    console.log(message);
}

或者您可以定义一个单独的函数(不适用于 this,但可以与其他变量一起使用).

Or you could define a separate function (won't work with this but will work with other variables).

element.addEventListener("hover", logFooOnInput, false);
function logOnInput(triggeredElement){
    console.log(triggeredElement);
}
function logFooOnInput() {
    logOnInput(foo);
}

或者你可以使用 bind.

Or you could use bind.

element.addEventListener("hover", logOnInput.bind(null, foo), false);
function logOnInput(message){
    console.log(message);
}

这篇关于Javascript,addEventListener 回调函数立即执行且仅执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆