[英]Console Error: Uncaught TypeError: Cannot read property 'top' of undefined
I'm trying to get a div class to scroll to the top when .recipeImgs li
is clicked. 我正在尝试单击.recipeImgs li
时.recipeImgs li
div类滚动到顶部。 I tried the code below but i am getting the error
message 我尝试了下面的代码,但收到error
消息
Uncaught TypeError: Cannot read property 'top' of undefined". Not sure how to fix the issue
Thanks 谢谢
$('.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;
});
});
The issue, as someone pointed out in one of the comments, is that $target
has no element, which means that the .offset()
method returns undefined
. 正如有人在其中一项注释中指出的那样,问题是$target
没有元素,这意味着.offset()
方法返回undefined
。 Obviously there is no property top
on undefined
, hence the error. 显然, undefined
上没有属性top
,因此是错误的。
You might reconsider writing your function something like this: 您可能会重新考虑编写如下函数:
$(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]';
})
});
This fixes several things. 这修复了几件事。 First of all, it delegates the listener to the document
, so if your li
is dynamically appended, you'll still be able to grab the event (as it bubbles up the DOM). 首先,它将侦听器委派给document
,因此,如果您的li
是动态附加的,您仍然可以抓取该事件(因为它使DOM冒泡)。 There's also a check for $target.length
. 还有一个$target.length
。 This just ensures that you don't try to retrieve the offset of an empty collection, resulting in an error and breaking your code. 这只是确保您不尝试检索空集合的偏移量,从而导致错误并破坏代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.