Uncaught TypeError:无法读取未定义的属性“top” [英] Uncaught TypeError: Cannot read property 'top' of undefined

查看:2272
本文介绍了Uncaught TypeError:无法读取未定义的属性“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; 发出一个错误Uncaught TypeError:的未定义。事实上,没有其他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.

推荐答案

偏移:

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

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

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