简体   繁体   English

jQuery 控制台错误:无法读取未定义的属性“top”

[英]jQuery Console Error: Cannot read property 'top' of undefined

This script smooth scrolls my #anchor links and creates the appropriate offset due to a fixed header that varies in height.此脚本平滑滚动我的 #anchor 链接并由于高度不同的固定标题创建适当的偏移量。

After a few hours of troubleshooting/researching this, I cannot figure out why 'top' is undefined.经过几个小时的故障排除/研究后,我无法弄清楚为什么 'top' 未定义。 Everything works as expected , but this error always occurs when I click the nav (a.anchorlink) from another page .一切都按预期工作,但是当我从另一个页面单击导航 (a.anchorlink) 时,总是会发生此错误。 Just before the page loads, this error pops up in the console.就在页面加载之前,控制台中会弹出此错误。 When the page then loads, this error is gone.当页面加载时,这个错误消失了。

jQuery: jQuery:

jQuery(document).ready(function($){
    var $root = $('html, body');

    function getFixedOffset($) {
        if($(window).scrollTop() === 0) {
            return 100;
        }
        else {
            return 55;
        }
    }

    $('a.anchorlink').click(function() {
        var href = $.attr(this, 'href');
        var targetID = href.substr(href.indexOf("#") + 1);

        if (targetID.length) {
            var lengthID = $("#" + targetID).offset().top;

            $root.animate({
                scrollTop: lengthID - getFixedOffset($)
            }, 850, function() {
                window.location.hash = lengthID;
            });
            return false;
        }
    });
})

HTML: HTML:

<ul class="menu">
  <li"><a href="/about#mission" class="anchorlink">Sub-link 1</a></li>
  <li"><a href="/about#history" class="anchorlink">Sub-link 2</a></li>
</ul>
<!-- All other pages don't have hashes and will spit the error before load -->

As you can see, I've ensured targetID exists (is not zero) in order to request the top property.如您所见,为了请求 top 属性,我已确保 targetID 存在(不为零)。 Are there additional steps I can take or would you need more information about the page that is spitting the error?是否有我可以采取的其他步骤,或者您是否需要有关吐出错误的页面的更多信息?

I suggest to you do the next because of probably you element target doesn't exists:我建议你做下一个,因为你的元素目标可能不存在:

if (targetID.length && $("#" + targetID).length > 0) {...

You only was verifying the href's content but not if the element in DOM exists.您只是在验证 href 的内容,而不是验证 DOM 中的元素是否存在。 So, with this double check, you ensure to try to do something with an non existent element.因此,通过这种双重检查,您可以确保尝试对不存在的元素执行某些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM