addEventListener回调函数立即执行

addEventListener回调函数立即执行

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

问题描述

我注意到addEventListener的回调在函数函数()之间存在差异。
在尝试传递参数之前,这不是问题。基本上,

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);
}


推荐答案

(如果你真的想要触发元素,不传递任何内容。将自动设置为触发元素。)

(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);
}

或者你可以定义一个单独的函数(不适用于这个但可以使用其他变量。)

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);
}

或者你可以使用。

Or you could use bind.

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

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

08-23 16:23