【问题标题】:Access Objects inside function访问函数内部的对象
【发布时间】: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


【解决方案1】:

我敢打赌,因为 $(".equalHeights .section").length 在对象创建时被调用,可能不会等待 DOM 被创建,所以 HTML 尚不可用,因此找不到元素。

所以,要么将所有代码包装到 $(function () { ... }) 中,以便在函数执行时完成 DOM(因此你可以摆脱 IIFE),或者让 init 函数启动 jQuery 元素选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多