簡體   English   中英

jQuery 控制台錯誤:無法讀取未定義的屬性“top”

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

此腳本平滑滾動我的 #anchor 鏈接並由於高度不同的固定標題創建適當的偏移量。

經過幾個小時的故障排除/研究后,我無法弄清楚為什么 'top' 未定義。 一切都按預期工作,但是當我從另一個頁面單擊導航 (a.anchorlink) 時,總是會發生此錯誤。 就在頁面加載之前,控制台中會彈出此錯誤。 當頁面加載時,這個錯誤消失了。

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:

<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 -->

如您所見,為了請求 top 屬性,我已確保 targetID 存在(不為零)。 是否有我可以采取的其他步驟,或者您是否需要有關吐出錯誤的頁面的更多信息?

我建議你做下一個,因為你的元素目標可能不存在:

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

您只是在驗證 href 的內容,而不是驗證 DOM 中的元素是否存在。 因此,通過這種雙重檢查,您可以確保嘗試對不存在的元素執行某些操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM