无法将事件传递到addEventListener:closure问题 [英] Can't pass event to addEventListener: closure issue
问题描述
这让我疯狂...我有一个循环,它添加一个事件监听器到SVG对象。对象是,为了讨论的缘故,一个小圆圈,我必须为10个圈子中的每一个添加mouseover和mouseout事件。
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.
我的第一个问题是标准闭包范围的事情 - 因为所有的侦听器都添加在同一个循环中,他们都看到循环变量的相同的无效值。我可以解决这个问题,我想,但第二个问题是,我必须传递'事件'给听众,我找不到任何方法同时解决这两个问题。
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.
我尝试过各种版本:
for(month = 0; month < nMonths; month++) {
...
shape.addEventListener(
"mouseover",
(function(event, index) { popup_on(event, foo, index); })(event, month),
false);
group.appendChild(shape);
}
这个特定版本给了我'事件未定义'。 popup_on
是真正的处理程序,必须得到 event
和当前值 month
。任何想法如何我应该这样做?感谢。
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.
推荐答案
事件将自动传递给您的函数 - 使它成为第一个参数到传递给 addEventListener
的函数。此外,false是捕获参数的默认值。
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.
(function() {
var i = month;
shape.addEventListener("mouseover", function(e) { popup_on(e, foo, i); });
})();
此外, foo
在你的事件回调中关闭?如果没有,你可以做同样的事情
Also, are you ok with foo
being closed over in your event callback? If not, you could do the same thing with it
(function() {
var i = month;
var f = foo;
shape.addEventListener("mouseover", function(e) { popup_on(e, f, i); });
})();
如果所有这些局部变量都变得烦人,你可以让他们的参数,更多tidy
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);
这篇关于无法将事件传递到addEventListener:closure问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!