情况有点像

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

问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。


当前回答

Use

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

如果你想传递任何自定义值到这个匿名函数那么最简单的方法是

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

在我的项目中完美地工作。希望这能有所帮助

其他回答

这里还有另一种方法(它在for循环中工作):

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

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

false);

这个问题很老了,但我想我可以使用ES5的.bind()为后代提供一个替代方案。:)

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

请注意,您需要设置listener函数,将第一个参数作为传递给bind(您的另一个函数)的参数,第二个参数现在是事件(而不是第一个,因为它本来就是)。

您可以通过将函数声明为变量来添加和删除带有参数的事件侦听器。

myaudio.addEventListener(’ended’、funcName =功能(false) (newSrc myaudio)});

newSrc是以myaudio为参数的方法 funcName是函数名变量

可以使用删除侦听器 myaudio.removeEventListener(“结束”,func假);

你可以用'bind'绑定所有必要的参数:

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

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

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

someevar值应该只能在some_function()上下文中访问,而不能从侦听器的上下文中访问。 如果你想在监听器中拥有它,你必须这样做:

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

并使用newVar代替。

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

var someVar = some_function(someVar);