情况有点像

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

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


当前回答

我建议你这样做:

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

其他回答

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

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

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

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

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

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

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

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