2011-12-23 83 views
0

任何人都可以告訴我爲什麼這不起作用?jQuery每個與SetTimeout

jeMarkers是一組Google地圖標記。

function toggleBounce() { 
    var bcounter = 0; 
    $(jeMarkers).each(function() { 
     setTimeout(function() { 
      if (this.getAnimation() != null) { 
       this.setAnimation(null); 
      } else { 
       this.setAnimation(google.maps.Animation.BOUNCE); 
      } 
     }, bcounter * 100); 
     bcounter++; 
    }); 
} 

如果我沒有setTimeout函數它的工作原理,但顯然同樣做的所有標記一次:

function toggleBounce() { 
    $.each(jeMarkers, function() { 
     if (this.getAnimation() != null) { 
      this.setAnimation(null); 
     } else { 
      this.setAnimation(google.maps.Animation.BOUNCE); 
     } 
    }); 
+0

在'$ .each'而不是'$(「element」)。each()'中嘗試setTimeout。 – Purag 2011-12-23 10:21:05

回答

2

你必須緩存函數內this對象,因爲該setTimeout的上下文不是自動設置的:

function toggleBounce() { 
    var bcounter = 0; 
    $(jeMarkers).each(function() { 
     var that = this; // <- Cache the item 
     setTimeout(function() { 
      if (that.getAnimation() != null) { 
       that.setAnimation(null); // <- Now we can call stuff on the item 
      } else { 
       that.setAnimation(google.maps.Animation.BOUNCE); 
      } 
     }, bcounter * 100); 
     bcounter++; 
    }); 
} 
+2

這被稱爲閉包(例如:*「JavaScript圍繞'var創建閉包''*),它是JavaScript最有用的特性之一。更多關於關閉:https://developer.mozilla.org/en/JavaScript/Guide/Closures – PPvG 2011-12-23 10:23:30

+0

PPvG是對的,我應該明確提到:) – mfeineis 2011-12-23 10:27:56

+0

就是這樣!我很確定我在所有的嘗試中都做了類似的事情,但我顯然沒有把它做對。非常感謝!! – Brigante 2011-12-23 10:30:57