情况有点像

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

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

其他回答

其他替代方法,可能没有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);
}

它已经测试了谷歌chrome扩展和可能e.srcElement必须替换为e.srcElement在其他浏览器

我发现这个解决方案使用Imatoria发布的评论,但我不能标记为有用的,因为我没有足够的声誉:D

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

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

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

false);

function. prototype.bind()是将目标函数绑定到特定作用域并可选地在目标函数中定义this对象的方法。

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

或者捕获一些词法范围,例如在循环中:

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

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

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

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

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

所以,我们可以修复上面的问题如下,它在所有浏览器工作良好

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

希望对在生产环境下压缩js文件的人有用。

祝你好运! !

你可以通过一个被称为闭包的javascript特性通过值(而不是引用)传递somevar:

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

或者你也可以写一个普通的包装函数,比如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'

这里wrapEventCallback(func,var1,var2)是这样的:

func.bind(null, var1,var2)