情况有点像

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

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


当前回答

这个解决方案可能很好看

var some_other_function = someVar => function() {
}

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

或者绑定变量也不错

其他回答

一个简单的方法就是这样

    window.addEventListener('click', (e) => functionHandler(e, ...args));

对我有用。

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

也可以试试这些(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

希望没有拼写错误:-)

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

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

并使用newVar代替。

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

var someVar = some_function(someVar);

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

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

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