【问题标题】:Why am I getting "Uncaught TypeError: Cannot read property 'body' of undefined"?为什么我会收到“未捕获的类型错误:无法读取未定义的属性 'body'”?
【发布时间】:2015-11-04 00:58:48
【问题描述】:

我的JS文件很简单

jQuery(function ( $ ) {
    // make elements with class 'same-height-as-width' have the self-explanatory property
    $(window).resize(function ( ) {
        $('.same-height-as-width').each( function ( ) {
            var thisElement = $(this);
            thisElement.height(thisElement.width());        
        });
    });

    window.onscroll = function () {

        var body = document.body; //IE 'quirks'
        var document = document.documentElement; //IE with doctype
        document = (document.clientHeight) ? document : body;

        if (document.scrollTop == 0) {
            alert("top");
        }
    };

});

给我带来麻烦的是var body = document.body; //IE 'quirks'。错误

未捕获的类型错误:无法读取未定义的属性“正文”

每次滚动时都会打印到控制台。然而,当我在控制台中输入document.body 时,控制台中显示的元素不是undefined。我也尝试将 window.onscroll 移到 jQuery(function ( $ ) 之外,但我得到了同样的错误。

【问题讨论】:

标签: javascript jquery dom javascript-events event-handling


【解决方案1】:

那是因为JavaScript variable hoisting,但不要让您感到困惑,不要使用“文档”作为变量的名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2016-10-05
    • 2021-10-06
    • 1970-01-01
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    相关资源
    最近更新 更多