使用jquery选择元素附近的第一个h2

Select the first h2 near a element with jquery

本文关键字:第一个 h2 jquery 选择 元素 使用      更新时间:2023-09-26

我真的是JS和JQuery的新手,我选择动画元素失败了,这是我的HTML

    <div class="box-product">
      <h2>Light</h2>
      <figure>
        <img src="img/boxes/light.jpg" alt="Pepper Box Light" title="Pepper Box Light" />
        <figcaption>
          Versão light, porém igualmente apimentada da nossa PepperBox, para quem quer se divertir com seu amor</figcaption>
      </figure>          
    </div><!-- box-product -->

当用户悬停在figure上时,我试图选择h2,所以这是我的最佳猜测:

    $('.box-product figure').hover(function() {
    $('.box-product').closest('h2').animate({color: 'f00'}, 'slow')
}, function() {
    $('.box-product').closest('h2').animate({color: 'inherit'}, 'slow')
});

但是什么都没发生,所以,我需要一些帮助。

谢谢!

closest():

获取与选择器匹配的第一个元素,从当前元素开始,向上遍历DOM树。

您可以使用prev()方法:

$('.box-product figure').hover(function() {
   $(this).prev().animate({color: '#f00'}, 'slow')
}, function() {
   $(this).prev().animate({color: 'inherit'}, 'slow')
});

或:

$('.box-product figure').hover(function() {
   $(this).siblings('h2').animate({color: '#f00'}, 'slow')
}, function() {
   $(this).siblings('h2').animate({color: 'inherit'}, 'slow')
});

使用.prev(),因为所需的h2figure的前一个同级,.closest()会搜索所选项目的祖先以查找匹配项。

$('.box-product figure').hover(function() {
    $h2 = $(this).prev('h2');
    $h2.animate({color: '#f00'}, 'slow')
}, function() {
    $h2.animate({color: '#000'}, 'slow')
});

FIDDLE

closest()返回dom树中父节点中的元素。您将需要siblings("h2")或仅需要prev()来获得悬停的<figure>:之前的元素

$('.box-product figure').hover(function() {
     $(this).prev().animate({color: 'f00'}, 'slow')
}, function() {
    $(this).prev().animate({color: 'inherit'}, 'slow')
});

从选择器$('.box-product')开始,您可以使用find("h2")children("h2"),但这将选择整个文档中的所有内容。如果你的盒子是独一无二的,你也可以使用类似$("#box-product h2")的东西。

h2figure的兄弟。

$('.box-product figure').hover(function() {
    $(this).siblings('h2').animate({color: '#f00'}, 'slow')
}, function() {
    $(this).siblings('h2').animate({color: 'inherit'}, 'slow')
});

试试这个。。。最近的第一个元素。。。

​$('h2').siblings(':first')​;​

Fiddle

closest()方法从父层次结构中查找最接近的匹配,而不是从子元素或同级元素中查找。

在您的情况下,您只需要从父元素中查找子元素。像这样:

 $('.box-product figure').hover(function() {
     $(this).closest('.box-product').find('h2').animate({color: 'f00'}, 'slow')
 }, function() {
     $(this).closest('.box-product').find('h2').animate({color: 'inherit'}, 'slow')
 });