【发布时间】:2015-07-13 18:11:34
【问题描述】:
jQuery
$('.add-to-cart2').on('click', function () {
var cart = $('.cart');
var imgtodrag = $(this).parent('.item').find("img").eq(0);
if (imgtodrag) {
var imgclone = imgtodrag.clone()
.offset({
top: imgtodrag.offset().top,
left: imgtodrag.offset().left
})
.css({
'opacity': '0.5',
'position': 'absolute',
'height': '150px',
'width': '150px',
'z-index': '100'
})
.appendTo($('body'))
.animate({
'top': cart.offset().top + 10,
'left': cart.offset().left + 10,
'width': 75,
'height': 75
}, 1000, 'easeInOutExpo');
setTimeout(function () {
cart.effect("shake", {
times: 2
}, 200);
}, 1500);
imgclone.animate({
'width': 0,
'height': 0
}, function () {
$(this).detach()
});
}
});
HTML
<li>
<div class="polaroid item">
<p>
<button class="add-to-cart2" type="button">
Add to cart
</button>
</p>
<img src="/img/rawr.png" alt="item">
</div>
</li>
错误
Uncaught TypeError: Cannot read property 'top' of undefined
嘿,
我找到了有关如何为购物车部分中的项目创建飞行动画的教程,但目前我收到一个错误,告诉我 offset.top 未定义。我试图解决它,我认为发生这种情况的原因是它找不到图像,所以变量“imgtodrag”没有任何东西可以拖动。
如果有人能看到代码中的错误,我会很高兴! :)
【问题讨论】:
-
你确定
imgtodrag不为空吗? -
你必须要么你的父母()或最近的()。 parent() 只是一个级别,因此它引用
元素。使用 parents() 或最接近的() 将解决您的问题。 parents() 将是一个更优化的解决方案,因为在这种情况下,您可以很确定“this”不是指项目 var imgtodrag = $(this).closest('.item').find("img").eq (0);或 var imgtodrag = $(this).parents('.item').find("img").eq(0); parents() 更好
-
因为您使用的是 parent(),所以 imgtodrag 为空,因此出现错误
标签: javascript jquery html