簡體   English   中英

無法讀取未定義的屬性“ top”

[英]Cannot read property 'top' of undefined`

我的網站上包含以下功能,僅在主頁上使用。 但是,當我轉到另一個不需要使用此功能的內部頁面時,出現Uncaught TypeError: Cannot read property 'top' of undefined控制台Uncaught TypeError: Cannot read property 'top' of undefined因為這些類不存在。 我可以添加一些代碼來防止控制台錯誤嗎?

$('.artist-kina').click(function( e ){
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $("#artists").offset().top - (
          $(window).width() < 450 ? 112 : 60
        )
    }, 500);
    $('.artists-home').fadeOut(function() {
        $('.kina-gallery').fadeIn('slow');
    });
});

您可以檢查與選擇器匹配的元素數。

$('.artist-kina').click(function( e ){
    e.preventDefault();
    e.stopPropagation();
    if ($("#artists").length > 1) {
        $('html, body').animate({
            scrollTop: $("#artists").offset().top - (
                $(window).width() < 450 ? 112 : 60
            )
        }, 500);
    }
    $('.artists-home').fadeOut(function() {
        $('.kina-gallery').fadeIn('slow');
    });
});

暫無
暫無

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

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