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参考
http://raphaeljs.com/reference.html#events
解决方法:
好吧,我对raphael库一无所知,但是似乎可以将c.hover包装在一个自调用函数中,以创建一个引用t正确值的闭包.
(function( local_t ) {
c.hover(function (event) {
this.animate({r: 13}, 200);
local_t.show();
}, function (event) {
this.animate({r: 10}, 200);
local_t.hide();
});
})( t );
这样,当您创建悬停事件处理程序时,它将传入t的值,并在内部将其引用为局部变量t_local(或您给它的任何名称),该变量将持续到调用处理程序之前(和之后). .
因此完整的代码将是:
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});
(function( local_t ) {
c.hover(function (event) {
this.animate({r: 13}, 200);
local_t.show();
}, function (event) {
this.animate({r: 10}, 200);
local_t.hide();
});
})( t );
}
编辑:您可以将for()语句的整个内部包装起来,但是我认为这不会对您在下面的评论中提到的特定Chrome问题产生影响.
for(var i = 0; i < feedData.length; i++){
(function( local_i ) {
var x = ( ( local_i + 1) * diff );
var t = r.text(x, 120, feedData[ local_i ].title).hide();
var c = r.circle(x, 150, 10);
c.attr({fill: "red"});
c.attr({stroke: "red"});
c.attr({title: feedData[ local_i ].title});
c.hover(function (event) {
this.animate({r: 13}, 200);
local_t.show();
}, function (event) {
this.animate({r: 10}, 200);
local_t.hide();
});
})( i );
}
标签:raphael,javascript 来源: https://codeday.me/bug/20191023/1915986.html