javascript - 为什么我收到 "Uncaught TypeError: Cannot read property ' body' of undefined”?

标签 javascript jquery dom event-handling jquery-events

我的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“怪癖”。错误

Uncaught TypeError: Cannot read property 'body' of undefined

每次滚动时

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

最佳答案

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

关于javascript - 为什么我收到 "Uncaught TypeError: Cannot read property ' body' of undefined”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31947906/

相关文章:

javascript - 在 Angular 5 中使用 Observable.ForkJoin 重复 Http 请求

javascript - 使用 jQuery 在页面加载时打开特定的引导选项卡

javascript - jQuery - 即使不满足条件也运行代码

javascript - 摊牌 highlightjs 扩展

javascript - jQuery 在 jsfiddle 中有效,但在 html 文件中无效?

html - Twitter Bootstrap html 选项卡如何工作?

javascript - 获取 API - 它是阻塞代码还是非阻塞代码?

javascript - HTML5 Canvas 调整到父级

javascript - 幻灯片放映在图像加载时开始,但在所有图像下载完成后才会显示第一张图像

javascript - JQuery 切换增值税切换