未捕获的类型错误:无法读取 null 的属性“nodeName”

问题描述

我有一个代码

(function($) {
$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {        // If page is scrolled more than 50px
        $('#return-to-top').fadeIn(200);    // Fade in the arrow
    } else {
        $('#return-to-top').fadeOut(200);   // Else fade out the arrow
    }
});
$('#return-to-top').click(function() {      // When arrow is clicked
    $('body,html').animate({
        scrollTop : 0                       // Scroll to top of body
    },500);
});
})(jQuery);

在 Chrome 中,我会截断页面。 然后我在控制台中收到一个错误

> Uncaught TypeError: Cannot read property 'nodeName' of null
>>    at _e (index.js:63)
>>>  at MutationObserver.<anonymous> (index.js:63)

wordpress 中的页面。有人可以帮忙吗?

解决方法

Cannot read property 'nodeName' of null 表明您尝试从 jQuery 访问的内容在脚本尝试访问它时不可用。

如果没有看到其余的代码,很难判断缺少什么,但作为起点,请确保您的 jQuery 函数被就绪函数的文档包围。

// A $( document ).ready() block.
$( document ).ready(function() {
    $(window).scroll(function() {
        if ($(this).scrollTop() >= 50) {        // If page is scrolled more than 50px
            $('#return-to-top').fadeIn(200);    // Fade in the arrow
        } else {
            $('#return-to-top').fadeOut(200);   // Else fade out the arrow
        }
    });
    $('#return-to-top').click(function() {      // When arrow is clicked
        $('body,html').animate({
            scrollTop : 0                       // Scroll to top of body
        },500);
    });
});

这确保代码块仅在 DOM 完全加载后运行。

,

该错误表明您正试图从您认为它是一个对象的空值变量中读取名为 nodeName 的属性。请检查代码的其他部分。

,

您收到此错误是因为在加载 DOM 之前加载了 javascript 库。确保首先加载您的 DOM。