2012-04-04 88 views

回答

2

把變量的函數外,比獲得比作在功能使用價值

var getWidth ; 
var getHeight ; 

$(function(){ 

    var slideBox = { 

     gb: $('#box'), 

     init: function() { 

       sb = this, 
       getBox = sb.gb, 
       getWidth = getBox.width(), 
       getHeight = getBox.height(); 
      getBox.animate({ marginLeft: '+='+getWidth }, 600); 

      $("#button").on("click", this.clickSlide); 
     }, 

     clickSlide: function() { 

      getBox.animate({ marginLeft: '+='+getWidth }, 600); 
     } 
    }; 

    slideBox.init(); 
}); 

讓你clickside功能

+0

我至少會把它們放在'ready'事件處理程序中,以便它們不是全局的。但無論如何,這隻允許有一個幻燈片對象。 – 2012-04-04 08:28:57

1

如果你是要去使用它們,你可以得到vlue很多,我會讓他們成爲對象的屬性。

+0

全球是全球性的。這與關閉有什麼關係?無論如何,我認爲使它們屬性的對象是最好的解決方案。 – 2012-04-04 08:28:30

+0

你說得對。我錯過了這一點。 – 2012-04-04 15:54:52

0

您的變量看起來沒有必要,您可以訪問您需要的所有內容: http://jsfiddle.net/4WfZa/6/。如果您確實需要存儲它們,則可以將它們添加到slideBox對象中,然後將它們填充到init中。這樣,變量就會存儲在對象中,並且可以用在其中的任何函數中。

有關javascript命名空間的一篇很好的文章,包括如何設置私有變量和公共變量,請參見this article