[英]Access Objects inside function
我是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,該值是不確定的。 有人可以幫幫我嗎。 提前致謝。
我敢打賭,因為$(".equalHeights .section").length
是在對象創建時調用的,而對象創建可能不會等待DOM的創建,因此HTML尚不可用,因此找不到元素。
因此,可以將所有代碼包裝到$(function () { ... })
以便在函數執行時完成DOM(因此可以擺脫IIFE),或者使init
函數啟動jQuery元素選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.