在 jquery 中查找远方父项

Find distant parent in jquery

我对如何追踪树上的元素作为父元素有点困惑。

$('.btn-action').hover(
  function(){
    $(this).find('.product-card').addClass('animated bounce');
  },
  function(){
    $(this).find('.product-card').removeClass('animated bounce')
  }
);

.product-card class 不是直接父级,而是更上层的父级。我需要根据 .btn-action class 上的悬停方法为其设置动画。这可以用 .parent().find() 实现吗?

要上树,您可以使用 .closest()。

$(this).closest('.product-card').addClass('animated bounce');

要在树中走得更远,请使用 .find()。 要保持同一水平,您可以使用 .siblings()

虽然我不确定你的类名中的 space。如果不需要多个 类,请尝试使用破折号。

我认为,您可以使用 .closest( selector ) 方法来获取元素的最近父级。

您尝试过使用 .parents() 吗? @see https://api.jquery.com/parents/

要获取 .product-card 祖先请尝试:

$('.product-card').parents()