无法读取未定义的链接 href 的属性“top”

Cannot read property 'top' of undefined of link href

本文关键字:属性 top href 链接 读取 未定义      更新时间:2023-09-26

我正在通过滚动为导航中的链接创建一个活动类。

    function onScroll(event){
        var scrollPosition = $(document).scrollTop();
        $('.sticky-navigation-posts a').each(function () {
            var currentLink = $(this);
            var refElement = $(currentLink.attr("href"));
            console.log(refElement);
            if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
                $('.sticky-navigation-posts .title-wrapper .post-title a').removeClass("active");
                console.log('yes!');
                currentLink.addClass("active");
            } else {
                currentLink.removeClass("active");
                console.log('no!');
            }
        });
    }

当我console.log(refElement)时,该元素被记录下来。但是如果我console.log(refElement.position().top),则此错误将抛Cannot read property 'top' of undefined。我已经调试了一段时间了,但无法弄清楚。有什么想法吗?我也尝试过将refElement包裹在$()中。
所有这些代码都是包装在$(document).ready()函数中。

好的,

我现在明白你的意思了。但是,它对我来说工作正常。不确定您在哪里遇到问题?

我添加了console.log(refElement.position().top);,它正在正确记录到控制台,甚至所需的行为也在工作!? http://jsfiddle.net/thesane/Dxtyu/3133/