情况有点像

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

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


当前回答

您编写的代码绝对没有任何问题。some_function和someVar都应该是可访问的,以防它们在匿名的上下文中可用

function() { some_function(someVar); } 

被创建。

检查警报是否为您提供了您一直在寻找的值,确保它可以在匿名函数的作用域内访问(除非您在addEventListener调用旁边有更多操作相同someVar变量的代码)

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

其他回答

    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();
    $form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
    function save(data, keyword, name, comment, event) {

这就是我如何正确地传递事件。

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

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

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

如果以后想要删除事件侦听器,那么创建对curry函数的引用是一个不错的选择。

在下面的代码中,我将说明我的意思。

// This is the curry function. We return a new function with the signature of what the click-listener expects
const handleClick = (foo, bar) => (clickEvent) => {
  console.log('we get our custom input', foo, bar);
  console.log('we get the click event too', clickEvent);
}

// We need to store a reference to the listener, making sure we are removing the correct reference later
const myListener = handleClick('foo', 'bar'); // Remember that we now return the actual event-handler


const btn = document.getElementById('btn'); // find the element to attach the listener to
btn.addEventListener('click', myListener);

// remove the event listener like this by using our reference
btn.removeEventListener('click', myListener);

下面是CodePen上的一个工作示例

你可以通过一个被称为闭包的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)