JavaScript 作用域问题导致只有一个绑定起作用
我正在使用 Raphael.js 库来完成特定的工作。我正在创建圆圈并绑定显示/隐藏文本的悬停事件。问题是,即使我将鼠标悬停在其他圆圈上,也仅显示/隐藏最后一个圆圈上的文本。
这是我的代码:
for(var i=0; i<feedData.length; i++){
var x = ((i+1)*diff);
var t = r.text(x, 120, feedData[i].title).hide();
var c = r.circle(x,150,10);
c.attr({fill: "red"});
c.attr({stroke: "red"});
c.attr({title: feedData[i].title});
c.hover(function (event) {
this.animate({r: 13}, 200);
t.show();
}, function (event) {
this.animate({r: 10}, 200);
t.hide();
});
}
对于 Raphael.js 参考
I am using Raphael.js library for a specific work. I am creating circles and binding hover event that show/hide text. The problem is that only the text over last circle is shown/hidden, even I am hovering over other circles.
Here is my code:
for(var i=0; i<feedData.length; i++){
var x = ((i+1)*diff);
var t = r.text(x, 120, feedData[i].title).hide();
var c = r.circle(x,150,10);
c.attr({fill: "red"});
c.attr({stroke: "red"});
c.attr({title: feedData[i].title});
c.hover(function (event) {
this.animate({r: 13}, 200);
t.show();
}, function (event) {
this.animate({r: 10}, 200);
t.hide();
});
}
For Raphael.js reference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,我对 raphael 库一无所知,但似乎您可以将
c.hover
包装在自调用函数中,以便创建一个引用正确值的闭包>t
。这样,当您创建
hover
事件处理程序时,它将传入t
的值,并在内部将其引用为局部变量t_local
(或者您给它起的任何名称),它将持续存在,直到调用处理程序(以及之后)。所以完整的代码是:
编辑:您可以将整个
for()
语句包装在里面,但我认为这不会对您在下面的评论中提到的具体Chrome
问题。Well, I don't know anything about raphael library, but it would seem that you could wrap your
c.hover
in a self calling function in order to create a closure that references the proper value oft
.This way, when you create your
hover
event handler, it will pass in the value oft
, and reference it inside as the local variablet_local
(or whatever name you give it), which will persist until (and after) the handler is called.So the full code would be:
EDIT: You could wrap the entire inside of the
for()
statement instead, but I don't think it will make a difference to the specificChrome
issue you mentioned in your comment below.似乎如果您将文本创建放在悬停事件本身内部,它可能会工作得更好一些。
it seems that if you place the text creation inside the hover event itself, it might work a little bit better.
看起来变量
t
不仅仅是对象,它还有hide()
。仅查看代码,我不确定在其他地方调用show()
或hide()
方法会发生什么。It looks like variable
t
isn't just the object, it's also gothide()
. Just looking at the code, I'm not sure what to expect from calling ashow()
orhide()
method on it elsewhere.