2017-08-02 122 views
2

我新來javascript,我需要一些指導。函數內的訪問對象

"use strict"; 
(function() { 

var maxHeightCalc = { 
    $maxHeight : 23, 
    $childElem : $(".equalHeights .section").length, 
    init : function() { 

     console.log(maxHeightCalc.$maxHeight); //prints 23 
     console.log(maxHeightCalc.$childElem); // prints undefined 

     for (var i=0; i<maxHeightCalc.$childElem.length; i++) { 
      console.log(i); 
     } 
    } 
}; 
$(function(){ 
    maxHeightCalc.init(); 
}) 

})(window); 

HTML結構

<body> 
    <div class="equalHeights"> 
     <h1>Equal heights with OOJS </h1> 
     <div class="section section-1"> 
      <h2>Section 1 </h2> 
      <p> 
       Lorem Ipsum is simply dummy text of the printing and typesetting industry. 

      </p> 
     </div> 

     <div class="section section-2"> 
      <h2>Section 2 </h2> 
      <p> 
       Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
       remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing 
       Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of 
       Lorem Ipsum. 
      </p> 
     </div> 

     <div class="section section-3"> 
      <h2>Section 3 </h2> 
      <p> 
       Lorem Ipsum i 
      </p> 
     </div> 
    </div> 
</body> 

我有兩個對象$ maxHeight和$ childElem。即時通訊嘗試訪問init函數內的兩個對象。我爲$ maxHeight獲取值,但對於$ childElem,值是未定義的。有人可以幫幫我嗎。提前致謝。

+0

你能顯示html嗎? –

+1

此代碼有效。如果我只是在我的控制檯中運行它,它會打印'23'和'0',然後打印'undefined',但是這是預期的,因爲該函數不返回任何東西,所以返回值是未定義的。 –

+0

感謝您的評論。如果你看到我的html,$(「。equalHeights .section」)。length必須返回3,但是現在它返回0,這個im面臨的問題 –

回答

0

我敢打賭,因爲$(".equalHeights .section").length被稱爲創建對象,可能不會等待創建DOM,HTML還不可用,因此找不到元素。

所以,無論是包裝所有的代碼到$(function() { ... })使DOM是在功能執行(你可以因此很可能擺脫IIFE的)來完成,或者使init功能啓動jQuery的元素選擇。