TypeError jQuery offset()。top未定义 [英] TypeError jQuery offset().top is undefined

查看:2283
本文介绍了TypeError jQuery offset()。top未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firefox调试器显示一个jQuery函数的TypeError,用于在用户同时滚动和更新类时将navbar粘贴到页面顶部。

The Firefox debugger is showing a TypeError for a jQuery function aimed at sticking a navbar to the to the top of the page when a user scrolls and updating the class at the same time.

函数如下。

$(window).scroll(function() {
    if ($(".navbar").offset().top>30) {
        $(".navbar-fixed-top").addClass("sticky");
    }
    else {
        $(".navbar-fixed-top").removeClass("sticky");
    }
});

产生的错误是这样的。


时间戳:31/01/2014 10:01:04

Timestamp: 31/01/2014 10:01:04

错误:TypeError: $(...) .offset(...)未定义

Error: TypeError: $(...).offset(...) is undefined

无法将结果转换为修复。

I have looked about on SO for a similar example but can not translate the outcomes into a fix. Any help would be greatly appreciated.

推荐答案

这是因为无法找到$(。navbar)。在获得偏移之前检查元素是否存在。

It 's because your $(".navbar") cannot be found. Check if the element exist before getting offset.

if ($(".navbar").length) {...}

这篇关于TypeError jQuery offset()。top未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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