在jquery中找到远程父级

时间:2017-07-21 20:17:00

标签: javascript jquery find parent

我有点坚持如何追踪一个以树为主要元素的元素。

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

.product-card类不是直接父级,而是在树的后面。我需要根据.btn-action类上的悬停方法为其设置动画。可以使用.parent().find()

来实现这一目标

3 个答案:

答案 0 :(得分:2)

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

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

要进一步使用树。使用.find()。 要保持同一级别,可以使用.siblings()

虽然我不确定你的类名中的空格。如果没有多个类,请尝试使用破折号。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

要获得.product-card祖先的尝试:

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