如何将参数传递给 addEventListener 侦听器函数? [英] How to pass arguments to addEventListener listener function?
问题描述
情况有点像-
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
问题是 someVar
的值在 addEventListener
的侦听器函数中是不可见的,它可能被视为一个新变量.
The problem is that the value of someVar
is not visible inside the listener function of the addEventListener
, where it is probably being treated as a new variable.
推荐答案
您编写的代码绝对没有问题.some_function
和 someVar
都应该是可访问的,以防它们在匿名
There is absolutely nothing wrong with the code you've written. Both some_function
and someVar
should be accessible, in case they were available in the context where anonymous
function() { some_function(someVar); }
已创建.
检查警报是否为您提供了您一直在寻找的值,确保它可以在匿名函数的范围内访问(除非您有更多代码对同一 someVar
变量进行操作在对 addEventListener
) 的调用旁边)
Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar
variable next to the call to addEventListener
)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
这篇关于如何将参数传递给 addEventListener 侦听器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!