我是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 :(得分:0)
我敢打赌,因为$(".equalHeights .section").length
在对象创建时调用,可能不等待创建DOM,所以HTML尚未可用,因此找不到元素。
因此,要么将所有代码都包装到$(function () { ... })
中,以便DOM在函数执行时完成(因此可以摆脱IIFE),或者使init
函数启动jQuery元素选择。