未捕获的TypeError: Cannot read property 'top'在引导中单击导航栏时未

Uncaught TypeError: Cannot read property 'top' of undefined while clicking on Navigation bar in bootstrap

本文关键字:单击 导航 top read Cannot property TypeError      更新时间:2023-09-26

单击导航菜单中创建的下拉菜单时,会抛出"Uncaught TypeError: Cannot read property 'top' of undefined"。有谁能帮我找出错误吗?

{以下是HTML代码深厚的软件

//这里有一些HTML代码

          <div class="collapse navbar-collapse" id="myNavbar">
            <ul class="nav navbar-nav">
              <li><a href="#section1">Home</a></li>
              <li><a href="#section2">Services</a></li>
              <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Portfolio<span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#section31">Animation</a></li>
                  <li><a href="#section32">WebSite Design</a></li>
                  <li><a href="#section33">Android Application</a></li>
                </ul>
              </li>
              <li><a href="#section4">Contact Us</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right top-right-padding">
            <li><a href="#" data-toggle="modal" data-target="#myModal">
            <span class="glyphicon glyphicon-user" ></span> Sign Up</a></li>
            <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
          </ul>
          </div>
        </div>
      </div>
    </nav> 

//java Script Code
          // Add scrollspy to <body>
          $('body').scrollspy({target: ".navbar", offset: 50});   
    
          // Add smooth scrolling on all links inside the navbar
          $("#myNavbar a").on('click', function(event) {
    
            // Prevent default anchor click behavior
            event.preventDefault();
    
            // Store hash
            var hash = this.hash;
            // Using jQuery's animate() method to add smooth page scroll
            // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
            $('html, body').animate({
    
              
              scrollTop: $(hash).offset().top
            
    
    
            }, 800, function(){
           
              // Add hash (#) to URL when done scrolling (default click behavior)
              window.location.hash = hash;
            });
          });

}

我已经添加了代码来检查哈希值,如果它是空的,那么不要做任何事情。

 // Store hash
    var hash = this.hash;
   if (hash.length != 0) {
    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $(hash).offset().top
    }, 800, function(){
      // Add hash (#) to URL when done scrolling (default click behavior)
      window.location.hash = hash;
    });
  }