如何将参数传递给addEventListener侦听器函数?

时间:2022-12-07 22:22:09

The situation is somewhat like-

情况有点像。

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.

问题是,someVar的值在addEventListener的侦听器函数中是不可见的,它可能被当作一个新的变量来处理。

21 个解决方案

#1


134  

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

您编写的代码完全没有问题。some_function和someVar都应该是可访问的,以防它们在匿名的环境中可用。

function() { some_function(someVar); } 

was created.

被创建。

Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

检查警报是否提供了您一直在寻找的值,请确保它在匿名函数的范围内是可访问的(除非您有更多的代码在调用addEventListener的同一个someVar变量上运行)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

#2


211  

Why not just get the arguments from the target attribute of the event?

为什么不从事件的目标属性中获取参数呢?

Example:

例子:

var someInput = document.querySelector('input');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';
function myFunc(evt)
{
  window.alert( evt.target.myParam );
}

JavaScript is a prototype-oriented language, remember!

JavaScript是一种面向原型的语言,请记住!

#3


31  

This question is old but I thought I'd offer an alternative using ES5's .bind() - for posterity. :)

这个问题已经过时了,但我想我可以用ES5的.bind()来为后代提供一个选择。:)

function some_func(otherFunc, ev) {
    // magic happens
}
someObj.addEventListener("click", some_func.bind(null, some_other_func), false);

Just be aware that you need to set up your listener function with the first param as the argument you're passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).

只需注意,您需要在第一个param中设置您的侦听器函数,作为您正在传递到bind(您的另一个函数)的参数,而第二个param现在是事件(而不是第一个,因为它本来是这样的)。

#4


16  

You can add and remove eventlisteners with arguments by declaring a function as a variable.

您可以通过声明一个函数作为变量来添加和删除eventlistener。

myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false);

myaudio.addEventListener(“结束”,funcName =函数(){ newSrc(myaudio)},假);

newSrc is the method with myaudio as parameter funcName is the function name variable

newSrc是使用myaudio作为参数的方法,它是函数名变量。

You can remove the listener with myaudio.removeEventListener('ended',func,false);

您可以用myaudio.removeEventListener('ended',func,false)将侦听器删除;

#5


10  

Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of currying.

很老的问题,但我今天遇到了同样的问题。我发现最干净的解决方案是使用currying这个概念。

The code for that:

的代码:

someObj.addEventListener('click', some_function(someVar));

var some_function = function(someVar) {
    return function curried_func(e) {
        // do something here
    }
}

By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.

通过命名curried函数,它允许您调用对象。removeEventListener在稍后的执行时间将eventListener注销。

#6


10  

You could pass somevar by value(not by reference) via a javascript feature known as closure:

您可以通过一个名为闭包的javascript特性(不是通过引用)传递somevar:

var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',function(someVar){
   return function(){func(someVar)}
}(someVar));
someVar='changed'

Or you could write a common wrap function such as wrapEventCallback:

或者您可以编写一个常见的包装函数,如wrapEventCallback:

function wrapEventCallback(callback){
    var args = Array.prototype.slice.call(arguments, 1);
    return function(e){
        callback.apply(this, args)
    }
}
var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'

Here wrapEventCallback(func,var1,var2) is like:

这里wrapEventCallback(func var1 var2):

func.bind(null, var1,var2)

#7


9  

someVar value should be accessible only in some_function() context, not from listener's. If you like to have it within listener, you must do something like:

someVar值应该仅在some_function()上下文中访问,而不是从侦听器的上下文。如果你想让它在听众里面,你必须做一些类似的事情:

someObj.addEventListener("click",
                         function(){
                             var newVar = someVar;
                             some_function(someVar);
                         },
                         false);

and use newVar instead.

和使用newVar代替。

The other way is to return someVar value from some_function() for using it further in listener (as a new local var):

另一种方法是从some_function()中返回someVar值,以便在侦听器中进一步使用它(作为一个新的本地var):

var someVar = some_function(someVar);

#8


8  

Here's yet another way (This one works inside for loops):

这里还有另一种方法(这一种方法适用于循环):

var someVar = some_other_function();
someObj.addEventListener("click", 

function(theVar){
    return function(){some_function(theVar)};
}(someVar),

false);

#9


6  

Use

使用

   el.addEventListener('click',
    function(){
        // this will give you the id value 
        alert(this.id);    
    },
false);

And if you want to pass any custom value into this anonymous function then the easiest way to do it is

如果您想要将任何自定义值传递到这个匿名函数中,那么最简单的方法就是。

 // this will dynamically create property a property
 // you can create anything like el.<your  variable>
 el.myvalue = "hello world";
 el.addEventListener('click',
    function(){
        //this will show you the myvalue 
        alert(el.myvalue);
        // this will give you the id value 
        alert(this.id);    
    },
false);

Works perfectly in my project. Hope this will help

在我的项目中效果很好。希望这将帮助

#10


5  

You may just bind all necessary arguments with 'bind':

你可以用“bind”来绑定所有必要的参数:

root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));

In this way you'll always get the event, arg1, and other stuff passed to myPrettyHandler.

通过这种方式,您将始终获得传递给myPrettyHandler的事件、arg1和其他内容。

http://passy.svbtle.com/partial-application-in-javascript-using-bind

http://passy.svbtle.com/partial-application-in-javascript-using-bind

#11


3  

Also try these (IE8 + Chrome. I dont know for FF):

试试这些(IE8 + Chrome)。我不知道FF):

function addEvent(obj, type, fn) {
    eval('obj.on'+type+'=fn');
}

function removeEvent(obj, type) {
    eval('obj.on'+type+'=null');
}

// Use :

function someFunction (someArg) {alert(someArg);}

var object=document.getElementById('somObject_id') ;
var someArg="Hi there !";
var func=function(){someFunction (someArg)};

// mouseover is inactive
addEvent (object, 'mouseover', func);
// mouseover is now active
addEvent (object, 'mouseover');
// mouseover is inactive

Hope there is no typos :-)

希望没有错别字:-)

#12


3  

Function.prototype.bind() is the way to bind a target function to a particular scope and optionally define the this object within the target function.

bind()是将目标函数绑定到特定范围的方法,并可在目标函数中定义该对象。

someObj.addEventListener("click", some_function.bind(this), false);

Or to capture some of the lexical scope, for example in a loop:

或者捕捉一些词汇范围,例如在一个循环中:

someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);

Finally, if the this parameter is not needed within the target function:

最后,如果目标函数中不需要该参数:

someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);

#13


2  

Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.

将参数发送到eventListener的回调函数需要创建一个孤立的函数,并将参数传递给该隔离函数。

Here's a nice little helper function you can use. Based on "hello world's" example above.)

这是一个很好的小助手函数。基于“hello world”的例子。

One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.

还有一件事是需要保持对函数的引用,这样我们就可以干净地删除侦听器。

// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running 
// within loops.
//
// The anonymous function returns a closure, that will be executed when 
// the event triggers. And since the arguments were captured, any vars 
// that were sent in will be unique to the function.

function addListenerWithArgs(elem, evt, func, vars){
    var f = function(ff, vv){
            return (function (){
                ff(vv);
            });
    }(func, vars);

    elem.addEventListener(evt, f);

    return f;
}

// Usage:

function doSomething(withThis){
    console.log("withThis", withThis);
}

// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");

// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);

#14


2  

One way is doing this with an outer function:

一种方法是用外函数来做:

elem.addEventListener('click', (function(numCopy) {
  return function() {
    alert(numCopy)
  };
})(num));

This method of wrapping an anonymous function in parentheses and calling it right away is called an IIFE (Immediately-Invoked Function Expression)

这种将匿名函数包装在括号中并立即调用它的方法称为IIFE(立即调用函数表达式)

You can check an example with two parameters in http://codepen.io/froucher/pen/BoWwgz.

您可以在http://codepen.io/froucher/pen/BoWwgz中查看一个带有两个参数的示例。

catimg.addEventListener('click', (function(c, i){
  return function() {
    c.meows++;
    i.textContent = c.name + '\'s meows are: ' + c.meows;
  }
})(cat, catmeows));

#15


2  

I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly

当我在一个循环中使用它来寻找元素并添加listner时,我陷入了这个困境。如果你在循环中使用它,那么它将会非常完美。

for (var i = 0; i < states_array.length; i++) {
     var link = document.getElementById('apply_'+states_array[i].state_id);
     link.my_id = i;
     link.addEventListener('click', function(e) {   
        alert(e.target.my_id);        
        some_function(states_array[e.target.my_id].css_url);
     });
}

#16


1  

    var EV = {
        ev: '',
        fn: '',
        elem: '',
        add: function () {
            this.elem.addEventListener(this.ev, this.fn, false);
        }
    };

    function cons() {
        console.log('some what');
    }

    EV.ev = 'click';
    EV.fn = cons;
    EV.elem = document.getElementById('body');
    EV.add();

//If you want to add one more listener for load event then simply add this two lines of code:

    EV.ev = 'load';
    EV.add();

#17


1  

The following approach worked well for me. Modified from here.

下面的方法对我很有效。从这里修改。

function callback(theVar) {
  return function() {
    theVar();
  }
}

function some_other_function() {
  document.body.innerHTML += "made it.";
}

var someVar = some_other_function;
document.getElementById('button').addEventListener('click', callback(someVar));
<!DOCTYPE html>
<html>
  <body>
    <button type="button" id="button">Click Me!</button>
  </body>
</html>

#18


0  

The following answer is correct but the below code is not working in IE8 if suppose you compressed the js file using yuicompressor. (In fact,still most of the US peoples using IE8)

下面的答案是正确的,但是如果假设您使用yuicompressor压缩了js文件,下面的代码在IE8中不起作用。(事实上,大多数美国人仍然使用IE8)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click",
                         function(){
                          some_function(someVar);
                         },
                         false);

So, we can fix the above issue as follows and it works fine in all browsers

因此,我们可以将上面的问题固定下来,在所有的浏览器中都可以正常工作。

var someVar, eventListnerFunc;
someVar = some_other_function();
eventListnerFunc = some_function(someVar);
someObj.addEventListener("click", eventListnerFunc, false);

Hope, it would be useful for some one who is compressing the js file in production environment.

希望,对于在生产环境中压缩js文件的人来说是很有用的。

Good Luck!!

祝你好运! !

#19


0  

The following code worked fine for me (firefox):

下面的代码对我来说很好(firefox):

for (var i=0; i<3; i++) {
   element = new ...   // create your element
   element.counter = i;
   element.addEventListener('click', function(e){
        console.log(this.counter);
        ...            // another code with this element
   }, false);
}

Output:

输出:

0
1
2

#20


-1  

Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop

另一种选择,可能不像使用bind那样优雅,但是它对循环中的事件是有效的。

for (var key in catalog){
    document.getElementById(key).my_id = key
    document.getElementById(key).addEventListener('click', function(e) {
        editorContent.loadCatalogEntry(e.srcElement.my_id)
    }, false);
}

It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers

它已经测试过谷歌的chrome扩展,也许还有e。srcElement必须被e替换。源在其他浏览器

I found this solution using the comment posted by Imatoria but I cannot mark it as useful because I do not have enough reputation :D

我使用了Imatoria发布的评论找到了这个解决方案,但我无法将其标记为有用,因为我没有足够的声誉:D。

#21


-1  

There is a special variable inside all functions: arguments. You can pass your parameters as anonymous parameters and access them (by order) through the arguments variable.

在所有函数中有一个特殊的变量:参数。您可以将参数作为匿名参数传递,并通过参数变量访问它们(按顺序)。

Example:

例子:

var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
    some_function(arguments[0]);
}, false);

#1


134  

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

您编写的代码完全没有问题。some_function和someVar都应该是可访问的,以防它们在匿名的环境中可用。

function() { some_function(someVar); } 

was created.

被创建。

Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

检查警报是否提供了您一直在寻找的值,请确保它在匿名函数的范围内是可访问的(除非您有更多的代码在调用addEventListener的同一个someVar变量上运行)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

#2


211  

Why not just get the arguments from the target attribute of the event?

为什么不从事件的目标属性中获取参数呢?

Example:

例子:

var someInput = document.querySelector('input');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';
function myFunc(evt)
{
  window.alert( evt.target.myParam );
}

JavaScript is a prototype-oriented language, remember!

JavaScript是一种面向原型的语言,请记住!

#3


31  

This question is old but I thought I'd offer an alternative using ES5's .bind() - for posterity. :)

这个问题已经过时了,但我想我可以用ES5的.bind()来为后代提供一个选择。:)

function some_func(otherFunc, ev) {
    // magic happens
}
someObj.addEventListener("click", some_func.bind(null, some_other_func), false);

Just be aware that you need to set up your listener function with the first param as the argument you're passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).

只需注意,您需要在第一个param中设置您的侦听器函数,作为您正在传递到bind(您的另一个函数)的参数,而第二个param现在是事件(而不是第一个,因为它本来是这样的)。

#4


16  

You can add and remove eventlisteners with arguments by declaring a function as a variable.

您可以通过声明一个函数作为变量来添加和删除eventlistener。

myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false);

myaudio.addEventListener(“结束”,funcName =函数(){ newSrc(myaudio)},假);

newSrc is the method with myaudio as parameter funcName is the function name variable

newSrc是使用myaudio作为参数的方法,它是函数名变量。

You can remove the listener with myaudio.removeEventListener('ended',func,false);

您可以用myaudio.removeEventListener('ended',func,false)将侦听器删除;

#5


10  

Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of currying.

很老的问题,但我今天遇到了同样的问题。我发现最干净的解决方案是使用currying这个概念。

The code for that:

的代码:

someObj.addEventListener('click', some_function(someVar));

var some_function = function(someVar) {
    return function curried_func(e) {
        // do something here
    }
}

By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.

通过命名curried函数,它允许您调用对象。removeEventListener在稍后的执行时间将eventListener注销。

#6


10  

You could pass somevar by value(not by reference) via a javascript feature known as closure:

您可以通过一个名为闭包的javascript特性(不是通过引用)传递somevar:

var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',function(someVar){
   return function(){func(someVar)}
}(someVar));
someVar='changed'

Or you could write a common wrap function such as wrapEventCallback:

或者您可以编写一个常见的包装函数,如wrapEventCallback:

function wrapEventCallback(callback){
    var args = Array.prototype.slice.call(arguments, 1);
    return function(e){
        callback.apply(this, args)
    }
}
var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'

Here wrapEventCallback(func,var1,var2) is like:

这里wrapEventCallback(func var1 var2):

func.bind(null, var1,var2)

#7


9  

someVar value should be accessible only in some_function() context, not from listener's. If you like to have it within listener, you must do something like:

someVar值应该仅在some_function()上下文中访问,而不是从侦听器的上下文。如果你想让它在听众里面,你必须做一些类似的事情:

someObj.addEventListener("click",
                         function(){
                             var newVar = someVar;
                             some_function(someVar);
                         },
                         false);

and use newVar instead.

和使用newVar代替。

The other way is to return someVar value from some_function() for using it further in listener (as a new local var):

另一种方法是从some_function()中返回someVar值,以便在侦听器中进一步使用它(作为一个新的本地var):

var someVar = some_function(someVar);

#8


8  

Here's yet another way (This one works inside for loops):

这里还有另一种方法(这一种方法适用于循环):

var someVar = some_other_function();
someObj.addEventListener("click", 

function(theVar){
    return function(){some_function(theVar)};
}(someVar),

false);

#9


6  

Use

使用

   el.addEventListener('click',
    function(){
        // this will give you the id value 
        alert(this.id);    
    },
false);

And if you want to pass any custom value into this anonymous function then the easiest way to do it is

如果您想要将任何自定义值传递到这个匿名函数中,那么最简单的方法就是。

 // this will dynamically create property a property
 // you can create anything like el.<your  variable>
 el.myvalue = "hello world";
 el.addEventListener('click',
    function(){
        //this will show you the myvalue 
        alert(el.myvalue);
        // this will give you the id value 
        alert(this.id);    
    },
false);

Works perfectly in my project. Hope this will help

在我的项目中效果很好。希望这将帮助

#10


5  

You may just bind all necessary arguments with 'bind':

你可以用“bind”来绑定所有必要的参数:

root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));

In this way you'll always get the event, arg1, and other stuff passed to myPrettyHandler.

通过这种方式,您将始终获得传递给myPrettyHandler的事件、arg1和其他内容。

http://passy.svbtle.com/partial-application-in-javascript-using-bind

http://passy.svbtle.com/partial-application-in-javascript-using-bind

#11


3  

Also try these (IE8 + Chrome. I dont know for FF):

试试这些(IE8 + Chrome)。我不知道FF):

function addEvent(obj, type, fn) {
    eval('obj.on'+type+'=fn');
}

function removeEvent(obj, type) {
    eval('obj.on'+type+'=null');
}

// Use :

function someFunction (someArg) {alert(someArg);}

var object=document.getElementById('somObject_id') ;
var someArg="Hi there !";
var func=function(){someFunction (someArg)};

// mouseover is inactive
addEvent (object, 'mouseover', func);
// mouseover is now active
addEvent (object, 'mouseover');
// mouseover is inactive

Hope there is no typos :-)

希望没有错别字:-)

#12


3  

Function.prototype.bind() is the way to bind a target function to a particular scope and optionally define the this object within the target function.

bind()是将目标函数绑定到特定范围的方法,并可在目标函数中定义该对象。

someObj.addEventListener("click", some_function.bind(this), false);

Or to capture some of the lexical scope, for example in a loop:

或者捕捉一些词汇范围,例如在一个循环中:

someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);

Finally, if the this parameter is not needed within the target function:

最后,如果目标函数中不需要该参数:

someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);

#13


2  

Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.

将参数发送到eventListener的回调函数需要创建一个孤立的函数,并将参数传递给该隔离函数。

Here's a nice little helper function you can use. Based on "hello world's" example above.)

这是一个很好的小助手函数。基于“hello world”的例子。

One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.

还有一件事是需要保持对函数的引用,这样我们就可以干净地删除侦听器。

// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running 
// within loops.
//
// The anonymous function returns a closure, that will be executed when 
// the event triggers. And since the arguments were captured, any vars 
// that were sent in will be unique to the function.

function addListenerWithArgs(elem, evt, func, vars){
    var f = function(ff, vv){
            return (function (){
                ff(vv);
            });
    }(func, vars);

    elem.addEventListener(evt, f);

    return f;
}

// Usage:

function doSomething(withThis){
    console.log("withThis", withThis);
}

// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");

// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);

#14


2  

One way is doing this with an outer function:

一种方法是用外函数来做:

elem.addEventListener('click', (function(numCopy) {
  return function() {
    alert(numCopy)
  };
})(num));

This method of wrapping an anonymous function in parentheses and calling it right away is called an IIFE (Immediately-Invoked Function Expression)

这种将匿名函数包装在括号中并立即调用它的方法称为IIFE(立即调用函数表达式)

You can check an example with two parameters in http://codepen.io/froucher/pen/BoWwgz.

您可以在http://codepen.io/froucher/pen/BoWwgz中查看一个带有两个参数的示例。

catimg.addEventListener('click', (function(c, i){
  return function() {
    c.meows++;
    i.textContent = c.name + '\'s meows are: ' + c.meows;
  }
})(cat, catmeows));

#15


2  

I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly

当我在一个循环中使用它来寻找元素并添加listner时,我陷入了这个困境。如果你在循环中使用它,那么它将会非常完美。

for (var i = 0; i < states_array.length; i++) {
     var link = document.getElementById('apply_'+states_array[i].state_id);
     link.my_id = i;
     link.addEventListener('click', function(e) {   
        alert(e.target.my_id);        
        some_function(states_array[e.target.my_id].css_url);
     });
}

#16


1  

    var EV = {
        ev: '',
        fn: '',
        elem: '',
        add: function () {
            this.elem.addEventListener(this.ev, this.fn, false);
        }
    };

    function cons() {
        console.log('some what');
    }

    EV.ev = 'click';
    EV.fn = cons;
    EV.elem = document.getElementById('body');
    EV.add();

//If you want to add one more listener for load event then simply add this two lines of code:

    EV.ev = 'load';
    EV.add();

#17


1  

The following approach worked well for me. Modified from here.

下面的方法对我很有效。从这里修改。

function callback(theVar) {
  return function() {
    theVar();
  }
}

function some_other_function() {
  document.body.innerHTML += "made it.";
}

var someVar = some_other_function;
document.getElementById('button').addEventListener('click', callback(someVar));
<!DOCTYPE html>
<html>
  <body>
    <button type="button" id="button">Click Me!</button>
  </body>
</html>

#18


0  

The following answer is correct but the below code is not working in IE8 if suppose you compressed the js file using yuicompressor. (In fact,still most of the US peoples using IE8)

下面的答案是正确的,但是如果假设您使用yuicompressor压缩了js文件,下面的代码在IE8中不起作用。(事实上,大多数美国人仍然使用IE8)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click",
                         function(){
                          some_function(someVar);
                         },
                         false);

So, we can fix the above issue as follows and it works fine in all browsers

因此,我们可以将上面的问题固定下来,在所有的浏览器中都可以正常工作。

var someVar, eventListnerFunc;
someVar = some_other_function();
eventListnerFunc = some_function(someVar);
someObj.addEventListener("click", eventListnerFunc, false);

Hope, it would be useful for some one who is compressing the js file in production environment.

希望,对于在生产环境中压缩js文件的人来说是很有用的。

Good Luck!!

祝你好运! !

#19


0  

The following code worked fine for me (firefox):

下面的代码对我来说很好(firefox):

for (var i=0; i<3; i++) {
   element = new ...   // create your element
   element.counter = i;
   element.addEventListener('click', function(e){
        console.log(this.counter);
        ...            // another code with this element
   }, false);
}

Output:

输出:

0
1
2

#20


-1  

Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop

另一种选择,可能不像使用bind那样优雅,但是它对循环中的事件是有效的。

for (var key in catalog){
    document.getElementById(key).my_id = key
    document.getElementById(key).addEventListener('click', function(e) {
        editorContent.loadCatalogEntry(e.srcElement.my_id)
    }, false);
}

It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers

它已经测试过谷歌的chrome扩展,也许还有e。srcElement必须被e替换。源在其他浏览器

I found this solution using the comment posted by Imatoria but I cannot mark it as useful because I do not have enough reputation :D

我使用了Imatoria发布的评论找到了这个解决方案,但我无法将其标记为有用,因为我没有足够的声誉:D。

#21


-1  

There is a special variable inside all functions: arguments. You can pass your parameters as anonymous parameters and access them (by order) through the arguments variable.

在所有函数中有一个特殊的变量:参数。您可以将参数作为匿名参数传递,并通过参数变量访问它们(按顺序)。

Example:

例子:

var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
    some_function(arguments[0]);
}, false);