情况有点像

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

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


当前回答

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

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

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

其他回答

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

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

并使用newVar代替。

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

var someVar = some_function(someVar);
    $form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
    function save(data, keyword, name, comment, event) {

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

我建议你这样做:

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

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

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

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

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

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