gpt4 book ai didi

javascript - 访问函数内部的对象

转载 作者:行者123 更新时间:2023-11-28 02:39:02 25 4
gpt4 key购买 nike

我是 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 元素选择。

关于javascript - 访问函数内部的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com