仅在页面上找到元素时,才能运行此代码?该功能在需要该功能的主页上运行良好;但是,在其他不需要该功能的页面上,控制台会在控制台中生成cannot read property .top of undefined...错误,因为我假设在页面上找不到这些元素。

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

最佳答案

if ($( "#music").length) {
    //Element exists
}

关于javascript - 仅在页面上找到元素时才运行功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26253234/

10-11 13:35