情况有点像

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

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


当前回答

为什么不直接从事件的目标属性获取参数呢?

例子:

const someInput = document.querySelector('button'); someInput。addEventListener('click', myFunc, false); someInput。myParam = '这是我的参数'; 函数myFunc (evt) { window.alert (evt.currentTarget.myParam); } <button class="input">显示参数</button>

JavaScript是一种面向原型的语言,记住!

其他回答

下面的代码为我工作良好(firefox):

for (var i=0; i<3; i++) {
   element = new ...   // create your element
   element.counter = i;
   element.addEventListener('click', function(e){
        console.log(this.counter);
        ...            // another code with this element
   }, false);
}

输出:

0
1
2

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

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

另一种解决方法是使用数据属性

function func(){
    console.log(this.dataset.someVar);
    div.removeEventListener("click", func);
}
    
var div = document.getElementById("some-div");
div.setAttribute("data-some-var", "hello");
div.addEventListener("click", 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

希望没有拼写错误:-)

我建议你这样做:

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