Scroll with navigation bar - Uncaught TypeError: Cannot read property 'top' of undefined

Scroll with navigation bar - Uncaught TypeError: Cannot read property 'top' of undefined

我在我的网站 console.log 中收到一条错误消息

Uncaught TypeError: Cannot read property 'top' of undefined

如果有人能看一下我已经得到的代码并帮助我找出问题所在。

当前代码:

HTML(导航栏)

<!-- Navigation buttons -->
<div class="collapse navbar-collapse navbar-right">
     <ul class="nav navbar-nav">
         <li class="scroll active"><a href="#home">Home</a></li>
         <li class="scroll"><a href="#services">Solutions</a></li>
         <li class="scroll"><a href="#features">Featured</a></li>
         <li class="scroll"><a href="#customers">Customers</a></li>
         <li class="scroll"><a href="#partners">Partners</a></li>
         <li class="scroll"><a href="#about">About</a></li>
         <li class="scroll"><a href="#meet-team">Team</a></li>
         <li class="scroll"><a href="#blog">Blog</a></li> 
         <li class="scroll"><a href="#get-in-touch">Contact</a></li>                        
     </ul>
</div>

JavaScript 和 JQuery

// Navigation Scroll
$(window).scroll(function(event)
{
    Scroll();
});

$('.navbar-collapse ul li a').on('click', function()
{
    $('html, body').animate(
    {
        scrollTop: $(this.hash).offset().top - 5
    }, 1000);
    return false;
});

// User define function
function Scroll()
{
    var contentTop = [];
    var contentBottom = [];
    var winTop = $(window).scrollTop();
    var rangeTop = 200;
    var rangeBottom = 500;
    $('.navbar-collapse').find('.scroll a').each(function()
    {
        contentTop.push($($(this).attr('href')).offset().top);
        contentBottom.push($($(this).attr('href')).offset().top + $($(this).attr('href')).height());
    })
    $.each(contentTop, function(i)
    {
        if (winTop > contentTop[i] - rangeTop)
        {
            $('.navbar-collapse li.scroll').removeClass('active').eq(i).addClass('active');
        }
    })
};

当你传递this.hash作为选择器时,意思就是,例如

$( '#about' );

这是一个 ID 选择器。但是你没有带 id="about" 的元素,所以没有选择任何元素。

两种可能的解决方案:或者为所有需要的元素提供集合 ID,或者使用属性选择器:

$('[href="' + this.hash + '"]')