Javascript JS-链接到带有锚定标记的主页

Javascript JS-链接到带有锚定标记的主页,javascript,html,jquery,Javascript,Html,Jquery,在我的prestashop网页上,我有一个带有锚的“一页”主页。我使用类linkscroll和JS脚本: $(document).ready(function() { $('.onas').attr('id', 'onas'); }); $(".linkscroll a").on('click', function(event) { if (this.hash !== "") { var hash = this.hash; $('h

在我的prestashop网页上,我有一个带有锚的“一页”主页。我使用类linkscroll和JS脚本:

$(document).ready(function() {
  $('.onas').attr('id', 'onas');
});
$(".linkscroll a").on('click', function(event) {
  if (this.hash !== "") {
    var hash = this.hash;
    $('html, body').animate({
      scrollTop: $(hash).offset().top
    }, 1000, function() {
      window.location.hash = hash;
    });
  }
});
在主页上,一切正常。但当我在产品页面上时,单击此链接后没有任何操作。Href为:“index.php#”

在控制台中,我看到错误:

Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLAnchorElement.<anonymous> (20-12-x-500ml-ekolok.html:1197)
at HTMLAnchorElement.dispatch (core.js:39)
at HTMLAnchorElement.g.handle (core.js:39)

欢迎请将
jQuery
或您正在使用的任何库添加到问题的标记中。谢谢。您的
this.hash
似乎是
未定义的。我想你应该把你的
点击
事件放在
文档中。准备好了
。谢谢你,我试图添加
点击
事件做
文档。准备好了
,但问题相同。请添加
如果(this.hash)
而不是
如果(this.hash!==”)
谢谢你@AnandBhushan,我像你写的那样编辑,但问题相同。
$(document).ready(function(){
$('.onas').attr('id', 'onas');
  
  $(".linkscroll a").on('click', function(event) { 
                                                                                                
     if(this.hash) {
     
      event.preventDefault();

      var hash = this.hash;

      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){
   
        window.location.hash = hash;
      });
    } 
  }); 
 });