javascript - 了解此控制台错误 - 'top' 未定义

标签 javascript jquery menu

所以我一直在使用这个功能来隐藏/显示带有 anchor 链接的滚动菜单。

它似乎按预期工作,但是我收到了一个恼人的控制台错误:

未捕获的类型错误:无法读取未定义的属性“top”。

有什么建议吗,我错过了什么?

$(document).ready(function () {
    "use strict";
    var a = !1,
        b = $(".menu-wrapper"),
        c = $(".menu a"),
        d = $(".intro-wrapper");
    b.hide(), $("a[href*=#]:not([href=#])").click(function () {
        var a = $(this.hash);
        return ($(this).addClass("active"), $("html, body").stop().animate({
            scrollTop: a.offset().top
        }, 1e3), !1);
    }),

    $(window).scroll(function () {
        var g = $(this).scrollTop(),
            h = $(this).height(),
            i = d.height();
        g >= i && !a ? (a = !0, b.stop().fadeIn()) : i > g && a && (a = !1, b.stop().fadeOut()), c.each(function () {
            var a = $(this.hash),
                b = a.offset().top,
                c = b + a.outerHeight();
            g + 1 > b && c > g + 1 ? $(this).addClass("active") : $(this).removeClass("active");
        });
    });
});

最佳答案

显然,这一行:

var a = $(this.hash);

...可能导致 jQuery 集合中没有任何内容(例如,this.hash 不识别页面上的任何元素)。当您在一个空的 jQuery 集上调用 offset 时,它会返回 undefined(与大多数其他 jQuery“getter”函数一样)。

所以要么:

  1. 确定为什么您期望的元素 $(this.hash) 不存在并修复它,或者

  2. a 是一个空的 jQuery 集时,请注意不要尝试使用 offset 的代码,例如:

    var a = $(this.hash);
    if (a[0]) {
        $(this).addClass("active");
        $("html, body").stop().animate({
            scrollTop: a.offset().top
        }, 1e3);
    }
    return false;
    

    或者如果你真的想像以前的代码一样缩小/混淆它:

    var a = $(this.hash);
    return (a[0] && ($(this).addClass("active"), $("html, body").stop().animate({
        scrollTop: a.offset().top
    }, 1e3)), !1);
    

关于javascript - 了解此控制台错误 - 'top' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29717787/

相关文章:

javascript - 设置 Iframe 的高度等于其内容

javascript - Angular promise 返回 "undefined"值 .NET MVC

javascript - 如何在聚焦时摆脱 React Native Paper TextInput 的底部边框

javascript - javascript或jquery中的自动标签切换

javascript - 对话框关闭按钮缺少样式?

javascript - Bootstrap selectpicker 不适用于 bootstrap "has-error"类

css - 在宽度变化时重新定位 DIV 菜单项

javascript - 如何使用 Node 从 POST 请求中获取同名复选框的值?

asp.net - CSS 与 IE6 下拉问题

WordPress wp_nav_menu - 将带有 <span> 的标题值添加到 <a> 中