javascript 无法将事件传递给 addEventListener:关闭问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8714472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't pass event to addEventListener: closure issue
提问by EML
This one's driving me crazy... I have a loop which adds an event listener to an SVG object. The object is, for the sake of argument, a small circle, and I have to add mouseover and mouseout events for each of the 10 circles.
这个让我发疯了......我有一个循环,它向一个 SVG 对象添加了一个事件监听器。为了便于论证,对象是一个小圆圈,我必须为 10 个圆圈中的每一个添加 mouseover 和 mouseout 事件。
My first problem is the standard closure-scope thing - because all the listeners are added in the same loop, they all see the same invalid value of the loop variable. I can fix this, I think, but the second problem is that I have to pass 'event' to the listeners, and I can't find any way to fix both these issues simultaneously.
我的第一个问题是标准的闭包作用域——因为所有的监听器都被添加到同一个循环中,它们都看到循环变量的相同无效值。我想我可以解决这个问题,但第二个问题是我必须将“事件”传递给侦听器,我找不到同时解决这两个问题的任何方法。
I've tried various versions of this:
我已经尝试了这个的各种版本:
for(month = 0; month < nMonths; month++) {
...
shape.addEventListener(
"mouseover",
(function(event, index) { popup_on(event, foo, index); })(event, month),
false);
group.appendChild(shape);
}
This particular version gives me 'event is not defined'. popup_on
is the real handler, and must get event
and the current value of month
. Any idea how I should be doing this? Thanks.
这个特定版本给了我'事件未定义'。popup_on
是真正的处理程序,必须获取event
和 的当前值month
。知道我应该怎么做吗?谢谢。
回答by Adam Rackis
The event will be passed to your function automatically—just make it the first argument to the function you pass to addEventListener
. Also, false is the default value for the capture parameter.
该事件将被传递给你的函数自动-只是将其作为第一个参数传递给函数addEventListener
。此外,false 是捕获参数的默认值。
(function() {
var i = month;
shape.addEventListener("mouseover", function(e) { popup_on(e, foo, i); });
})();
Also, are you ok with foo
being closed over in your event callback? If not, you could do the same thing with it
另外,您可以foo
在事件回调中关闭吗?如果没有,你可以用它做同样的事情
(function() {
var i = month;
var f = foo;
shape.addEventListener("mouseover", function(e) { popup_on(e, f, i); });
})();
And if all these local variables are getting annoying, you can make them parameters to possibly make things a bit more tidy
如果所有这些局部变量都变得烦人,您可以将它们设置为参数以使事情更整洁
(function(i, f) {
shape.addEventListener("mouseover", function(e) { popup_on(e, f, i); });
})(month, foo);