2010-09-13 54 views
3

我正在使用Raphael.js库进行特定的工作。我正在创建显示/隐藏文本的圈子和绑定悬停事件。问题是只有最后一圈的文字才会显示/隐藏,即使我在其他圈子上方悬停。JavaScript范围问题导致只有一个绑定工作

这里是我的代码:

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

回答

5

嗯,我不知道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); 

这样,当您创建hover事件处理程序,它会通过在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);   
} 
+0

不能在镀铬 – coure2011 2010-09-18 17:54:45

+0

@ coure06 - 什么部分不工作?这项技术是javascript的基本部分。在Chrome中不应该有任何不同。你确定它不是'raphael.js'库的其他问题吗? – user113716 2010-09-18 17:58:08

+0

检查它在http://bit.ly/bhLoNG [不在铬]工作 – coure2011 2010-09-18 17:59:37

0

看来,如果您将悬停事件本身中的文本创作,它可能工作一点点好一点。

0

它看起来像变量t不仅仅是对象,它也得到了hide()。只是看代码,我不知道在其他地方调用show()hide()方法会期待什么。

for(var i=0; i<feedData.length; i++){    
      var x = ((i+1)*diff); 
      var t = r.text(x, 120, feedData[i].title); //remove hide() method 
      var c = r.circle(x,150,10); 
      c.attr({fill: "red"}); 
      c.attr({stroke: "red"}); 
      c.attr({title: feedData[i].title}); 
      t.hide() //try it here instead? 
      c.hover(function (event) { 
       this.animate({r: 13}, 200); 
       t.show(); 
      }, function (event) { 
       this.animate({r: 10}, 200); 
       t.hide(); 
      });    
     }