javascript - 访问函数内部的对象

标签 javascript jquery html css oop

我是 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/

相关文章:

jquery - 将谷歌贝尔曲线图和条形图合二为一

jquery - 如何将 jquery 代码放入 html 文档中? (灯箱)

html - div css下的div不起作用

html - Div margin 将其插入内部

javascript - 在转换过程中隐藏背面的最佳方法是什么?

javascript - 如何将下拉列表设置为多个值?

javascript - 如何在 jQuery 子选择器中使用 event.target?

javascript - Fancybox 无法工作,并且控制台中没有错误

javascript - 如何导航到页面但确保目标页面将被刷新

javascript - JavaScript 游戏上的箭头键不起作用