Javascript 如何将参数传递给在 addEventListener 中使用的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12024483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:55:36  来源:igfitidea点击:

How to pass parameter to function using in addEventListener?

javascripthtmljavascript-events

提问by mko

In the traditional way to add event listener:

以传统方式添加事件监听器:

function getComboA(sel) {
    var value = sel.options[sel.selectedIndex].value;  
}

<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>

But I wanted to adapt to the addEventListener way:

但我想适应 addEventListener 的方式:

productLineSelect.addEventListener('change',getSelection(this),false);

function getSelection(sel){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
}

It doesn't work because I can't pass any parameter in getSelection() as the second parameter in addEventListener method? As far as I know I can only use the function name without parenthesises.

它不起作用,因为我无法将 getSelection() 中的任何参数作为 addEventListener 方法中的第二个参数传递?据我所知,我只能使用没有括号的函数名。

Any idea?

任何的想法?

BTW, please look at my previous questionabout console.log doesn't work in safari 6.0 developer inspector, I can't write any output in the console, which is frustrating.

顺便说一句,请查看我之前关于 console.log 在 safari 6.0 developer inspector 中不起作用的问题,我无法在控制台中写入任何输出,这令人沮丧。

回答by Joseph Silber

No need to pass anything in. The function used for addEventListenerwill automatically have thisbound to the current element. Simply use thisin your function:

无需传入任何内容。用于的函数addEventListener将自动this绑定到当前元素。只需this在您的函数中使用:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/

这是小提琴:http: //jsfiddle.net/dJ4Wm/



If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

如果要将任意数据传递给函数,请将其包装在您自己的匿名函数调用中:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/

这是小提琴:http: //jsfiddle.net/t4Gun/



If you want to set the value of thismanually, you can use the callmethodto call the function:

如果你想设置的值this手动,您可以使用call方法来调用该函数:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

回答by Jeffrey Westerkamp

In the first line of your JS code:

在 JS 代码的第一行:

select.addEventListener('change', getSelection(this), false);

you're invoking getSelectionby placing (this)behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.

您通过放置在函数引用后面来调用 getSelection(this)。这很可能不是您想要的,因为您现在正在将该调用的返回值传递给 addEventListener,而不是对实际函数本身的引用。



In a function invoked by addEventListenerthe value for thiswill automatically be set to the object the listener is attached to, productLineSelectin this case.

在这种情况下,在由addEventListener值调用的函数中,forthis将自动设置为侦听器附加到的对象productLineSelect

If that is what you want, you can just pass the function reference and thiswill in this example be selectin invocations from addEventListener:

如果这就是你想要的,你可以只传递函数引用,并且this在这个例子中将在select来自 addEventListener 的调用中:

select.addEventListener('change', getSelection, false);

If that is notwhat you want, you'd best bindyour value for this to the function you're passing to addEventListener:

如果这不是您想要的,那么您最好bind将此值用于传递给的函数addEventListener

var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);

The .bindpart is also a call, but this call just returns the same function we're calling bindon, with the value for thisinside that function scope fixedto thisArg, effectively overriding the dynamic nature of this-binding.

.bind部分也是一个调用,但这个调用只返回我们正在调用的相同函数bindthis该函数范围内的值固定thisArg,有效地覆盖了 this 绑定的动态特性。



To get to your actual question: "How to pass parameters to function in addEventListener?"

要解决您的实际问题:“如何将参数传递给 addEventListener 中的函数?”

You would have to use an additional function definition:

您将不得不使用额外的函数定义:

var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}, false);

Now we pass the event object, a reference to the value of thisinside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelectionfunction.

现在我们将事件对象、this对 addEventListener 回调内部的值的引用、在该回调内部定义和初始化的变量以及来自整个 addEventListener 调用外部的变量传递给您自己的getSelection函数。



We also might again have an object of our choice to be thisinside the outer callback:

我们也可能再次选择一个对象this位于外部回调中:

var thisArg = { custom: 'object' };
var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);

回答by Lee

When you use addEventListener, thiswill be bound automatically. So if you want a reference to the element on which the event handler is installed, just use thisfrom within your function:

使用时addEventListenerthis会自动绑定。因此,如果您想要引用安装了事件处理程序的元素,只需this在您的函数中使用:

productLineSelect.addEventListener('change',getSelection,false);

function getSelection(){
    var value = sel.options[this.selectedIndex].value;
    alert(value);
}

If you want to pass in some other argument from the context where you call addEventListener, you can use a closure, like this:

如果你想从你调用的上下文中传递一些其他参数addEventListener,你可以使用一个闭包,像这样:

productLineSelect.addEventListener('change', function(){ 
    // pass in `this` (the element), and someOtherVar
    getSelection(this, someOtherVar); 
},false);

function getSelection(sel, someOtherVar){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
    alert(someOtherVar);
}

回答by jfriend00

If the thisvalue you want is the just the object that you bound the event handler to, then addEventListener()already does that for you. When you do this:

如果this您想要的值只是您将事件处理程序绑定到的对象,那么addEventListener()已经为您完成了。当你这样做时:

productLineSelect.addEventListener('change', getSelection, false);

the getSelectionfunction will already be called with thisset to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

getSelection函数将已被调用并this设置为事件处理程序绑定到的对象。它还将传递一个参数,该参数表示具有有关该事件的各种对象信息的事件对象。

function getSelection(event) {
    // this will be set to the object that the event handler was bound to
    // event is all the detailed information about the event
}


If the desired thisvalue is some other value than the object you bound the event handler to, you can just do this:

如果所需的this值不是您将事件处理程序绑定到的对象的其他值,您可以这样做:

var self = this;
productLineSelect.addEventListener('change',function() {
    getSelection(self)
},false);

By way of explanation:

通过解释:

  1. You save away the value of thisinto a local variable in your other event handler.
  2. You then create an anonymous function to pass addEventListener.
  3. In that anonymous function, you call your actual function and pass it the saved value of this.
  1. 您将 的值保存this到其他事件处理程序中的局部变量中。
  2. 然后创建一个匿名函数来传递 addEventListener。
  3. 在该匿名函数中,您调用实际函数并将this.