情况有点像

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

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

其他回答

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

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

只是想添加。如果有人正在添加一个更新复选框到事件监听器的函数,你将不得不使用事件。目标替换此来更新复选框。

一种方法是用一个外部函数:

elem.addEventListener('click', (function(numCopy) {
  return function() {
    alert(numCopy)
  };
})(num));

这种将匿名函数包装在圆括号中并立即调用它的方法称为IIFE(立即调用函数表达式)。

您可以在http://codepen.io/froucher/pen/BoWwgz中查看带有两个参数的示例。

catimg.addEventListener('click', (function(c, i){
  return function() {
    c.meows++;
    i.textContent = c.name + '\'s meows are: ' + c.meows;
  }
})(cat, catmeows));

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

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

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

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

因为你的事件监听器是'click',你可以:

someObj.setAttribute("onclick", "function(parameter)");