2012-12-27 56 views
0

我聽說所有變量都需要在標準函數的頂部聲明。jquery - 變量是否只需要聲明頂部的函數?

但是,如果元素是在函數之間創建的,另一個元素取決於創建元素的寬度或高度(dynamicaly),我們如何在頂部聲明變量?

這是我的函數:

var stepSlider = function(holder,column){ 

    $.each(holder, function(i,value) { 

     var container = $(value), 
      colCount = column, 
      boardViewer = container.find('.stepRangeCompound'), 
      boardHolder = container.find('.boardHolder'), 
      board = container.find('.indBoard'), 
      boardCount = board.size(), 
      boardWidth = board.outerWidth(true), 
      boardHeight = board.outerHeight(true), 

      initial=0; 

     //setting sizes 

     while(initial < boardCount){ 
      if(initial % colCount === 0){ 
       $('<div />',{ 
        class:'boardColumn', 
        css:{ 
         float:'left', 
         height:boardHeight*colCount 
        } 
        }) 
       .appendTo(boardHolder) //after append only i am getting the width and element at all. 
      } 
      $('.boardColumn:last').append(board[initial]); 
      initial++; 
     } 

     var colWidth = $('.boardColumn').width(), //i am declaring variable here 
      coloSize = $('.boardColumn').size(); 

     boardViewer.css({ 
      width:colCount*colWidth // i am applying the values here. 
     }); 

     boardHolder.css({ 
      width:coloSize * colWidth // i am applying the values here. 
     }); 

    }) 
} 

,如果我錯了,任何一個指導我到申報只有在上面的所有變量的正確方法是什麼?

+1

這只是一個風格問題......不同的人和公司使用不同的規則。各有其優點和缺點。保持一致更重要。 –

回答

2

你可以在JavaScript中的蒼蠅聲明一個變量賦值。 無需申報。但即使如此,你想要聲明所有使用的變量在上面。你可以聲明它們爲空值然後給它們分配你想要的值

var colWidth,coloSize ; // on the top you declare 
. 
. 
. 
colWidth = $('.boardColumn').width(); // in the middle you assign them the value 
coloSize = $('.boardColumn').size(); 
+0

在嚴格模式下聲明變量是強制性的。如果您不以非嚴格模式進行操作,它們會變成全球性的,這是有效的,但可能會以某種方式破壞您的應用程序。 –

1

您可以在頂部聲明它們,空值,並且在創建元素時

相關問題