2010-09-13 49 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(); 
      });    
     }