控制台错误:未捕获类型错误:无法读取属性'top'的未定义
Console Error: Uncaught TypeError: Cannot read property 'top' of undefined
我正试图让一个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
的检查。这只是确保您不会试图检索空集合的偏移量,从而导致错误并破坏代码。
相关文章:
- webRTC错误未定义配置
- gmaps4rails 2.4.6未捕获引用错误:未定义Gmaps
- 未捕获引用错误:未定义validateform
- 为什么我会出现此错误"未捕获引用错误:未定义标题;
- Sitecore”;未捕获引用错误:未定义MultilistWithSearch;
- Wordpress:未捕获引用错误:未定义速度
- Node.js引用错误:未定义类名
- Replace()产生“;未捕获的类型错误:未定义的不是函数“;当与零一起使用时
- 错误-未定义easeInBounce
- 未捕获的引用错误:未定义<映射键>
- 未捕获的类型错误:未定义不是上的函数.GetElementByID
- Javascript错误:未捕获引用错误:未定义编辑
- javascript onchange取消绑定错误|未定义
- requirejs优化器错误:未定义窗口
- 未捕获引用错误:未定义PrintThisPage
- JSHint 错误:未定义我的应用程序 (W117)
- 当我编写脚本时,它显示引用错误:未定义宽度
- socket.io - 引用错误:未定义 io
- 反应.js:未捕获类型错误:未定义不是一个函数
- 出现“未捕获的类型错误:未定义不是函数”控制台错误