情况有点像

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

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


当前回答

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

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

斯菲德尔

其他回答

不错的一行选择

element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {

 //some action...

}

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

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

我建议你这样做:

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

您编写的代码绝对没有任何问题。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);

下面的答案是正确的,但如果你使用yuiccompressor压缩js文件,下面的代码在IE8中不能工作。(事实上,大多数美国人仍然在使用IE8)

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

所以,我们可以修复上面的问题如下,它在所有浏览器工作良好

var someVar, eventListnerFunc;
someVar = some_other_function();
eventListnerFunc = some_function(someVar);
someObj.addEventListener("click", eventListnerFunc, false);

希望对在生产环境下压缩js文件的人有用。

祝你好运! !