控制台错误:未捕获类型错误:无法读取属性'top'的未定义

Console Error: Uncaught TypeError: Cannot read property 'top' of undefined

本文关键字:错误 未定义 属性 top 类型 控制台 读取      更新时间:2023-09-26

我正试图让一个div类在单击.recipeImgs li时滚动到顶部。我尝试了下面的代码,但我得到了error消息

Uncaught TypeError: Cannot read property 'top' of undefined". Not sure how to fix the issue

感谢

$('.recipeImgs li').on('click',function (e) {
      e.preventDefault();
      console.log("clicked");
      var target = this.hash,
      $target = $(target);
      $('html, body').stop().animate({
          'scrollTop': $target.offset().top-50
      }, 900, 'swing', function () {
          window.location.hash = target;
     });
});
正如有人在其中一条评论中指出的那样,问题是$target没有元素,这意味着.offset()方法返回undefined。显然,undefined上没有属性top,因此出现了错误。

你可能会重新考虑这样写函数:

$(document).on('click', '.recipeImgs li', function(evt){
  evt.preventDefault();
  var $target = $(this);
  if(!$target.length) return;
  $('html, body')
    .stop()
    .animate({
      'scrollTop': $target.offset().top - 50
    }, 900, 'swing', function(){
      window.location.hash = '[target]';
    })
});

这修复了几个问题。首先,它将侦听器委托给document,因此,如果li是动态附加的,那么您仍然可以获取事件(因为它在DOM中冒泡)。还有一个$target.length的检查。这只是确保您不会试图检索空集合的偏移量,从而导致错误并破坏代码。