未捕获的类型错误:无法读取未定义的属性“top" [英] Uncaught TypeError: Cannot read property 'top' of undefined

查看:31
本文介绍了未捕获的类型错误:无法读取未定义的属性“top"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这个问题已经得到回答,我深表歉意.我试过寻找解决方案,但找不到任何适合我的代码的解决方案.我还是 jQuery 的新手.

I apologize if this question has already been answered. I've tried searching for solutions but could not find any that suited my code. I'm still new to jQuery.

对于两个不同的页面,我有两种不同类型的粘性菜单.这是两者的代码.

I have two different types of sticky menus for two different pages. Here's the code for both.

$(document).ready(function () {
    var contentNav = $('.content-nav').offset().top;
    var stickyNav = function () {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > contentNav) {
            $('.content-nav').addClass('content-nav-sticky');
        } else {;
            $('.content-nav').removeClass('content-nav-sticky')
        }
    };
    stickyNav();
    $(window).scroll(function () {
        stickyNav();
    });
});
$(document).ready(function () {
    var stickyNavTop = $('.nav-map').offset().top;
    // var contentNav = $('.content-nav').offset().top;
    var stickyNav = function () {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > stickyNavTop) {
            $('.nav-map').addClass('sticky');
            // $('.content-nav').addClass('sticky');
        } else {
            $('.nav-map').removeClass('sticky');
            // $('.content-nav').removeClass('sticky')
        }
    };
    stickyNav();
    $(window).scroll(function () {
        stickyNav();
    });
});

我的问题是底部粘性侧边菜单的代码不起作用,因为第二行代码 var contentNav = $('.content-nav').offset().top; 会触发一个错误,内容为未捕获的类型错误:无法读取未定义的属性 'top'".事实上,第二行下面的其他 jQuery 代码根本无法工作,除非它们被放置在它上面.

My problem is that the code for the sticky side menu on the bottom doesn't work because the second line of code var contentNav = $('.content-nav').offset().top; fires a error that reads "Uncaught TypeError: Cannot read property 'top' of undefined". In fact, no other jQuery code below that second line works at all unless they are placed above it.

经过一番研究,我认为问题在于 $('.content-nav').offset().top 找不到指定的选择器,因为它位于不同的页面上.如果是这样,我找不到解决方案.

After some researching, I think the problem is that $('.content-nav').offset().top can't find the specified selector because it's on a different page. If so, I can't find a solution.

推荐答案

在尝试获取其偏移量之前检查 jQuery 对象是否包含任何元素:

Check if the jQuery object contains any element before you try to get its offset:

var nav = $('.content-nav');
if (nav.length) {
  var contentNav = nav.offset().top;
  ...continue to set up the menu
}

这篇关于未捕获的类型错误:无法读取未定义的属性“top"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆