【问题标题】:jQuery offset().top is undefined [duplicate]jQuery offset().top 未定义 [重复]
【发布时间】: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


【解决方案1】:

你可以在没有parent()的情况下找到img

var imgtodrag = $(".add-to-cart2").find("img").eq(0);

【讨论】:

    【解决方案2】:

    您需要使用 closest() 而不是 parent()

    var imgtodrag = $(this).closest('.item').find("img").eq(0);
    

    因为.item 不是.add-to-cart2 的直接父级,所以parent() 只在DOM 树上向上移动一层。所以你需要使用 closest() ,它会沿着 DOM 树向上移动,直到找到匹配项。

    【讨论】:

    • 非常感谢!是否有原因它不适用于父母?
    • 你必须要么你的父母()或最近的()。 parent() 只是一个级别,因此它引用

      元素。使用 parents() 或最接近的() 将解决您的问题。 parents() 将是一个更优化的解决方案,因为在这种情况下,您可以非常确定“this”不是指 item。 var imgtodrag = $(this).closest('.item').find("img").eq(0);或 var imgtodrag = $(this).parents('.item').find("img").eq(0); parents() 更好。由于您使用的是 parent(),所以 imgtodrag 为空,因此错误

    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多