【发布时间】:2018-01-09 16:21:10
【问题描述】:
我是 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,这个价值是未定义的。有人可以帮帮我吗。提前致谢。
【问题讨论】:
-
你也可以显示html吗?
-
此代码有效。如果我只是在控制台中运行它,它会打印
23和0,然后是undefined,但这是预期的,因为该函数不返回任何内容,因此返回值未定义。 -
感谢您的评论。如果你看到我的 html,$(".equalHeights .section").length 必须返回 3,但现在它返回 0,这就是我面临的问题
-
只有在显示的脚本位于正文标签底部时才有效,否则当您设置
$childElem时$(".equalHeights .section")不存在。可以在init()内设置$childElem,因为它是在文档准备好后调用的 -
谢谢,将脚本文件放在正文标记后,它工作正常。
标签: javascript jquery html css oop