Jquery 选择器元素内部的其他

Jquery selector element inside other

本文关键字:其他 内部 元素 选择器 Jquery      更新时间:2023-09-26

我在尝试构建一个漂亮的"产品"页面时遇到问题,我有html:

    <div class="product-box-2">
     <a href="img/produtos/1-lightbox.jpg" class="lightbox"><img src="img/produtos/1.jpg" alt=""></a>
     <p class="legend">>> Vero mlkshk velit, freegan ullamco commodo put a bird on it cred synth kogi, Vero mlkshk velit, freegan ullamco commodo put a bird on it cred synth kogi.</p>
     <a href="img/produtos/1-lightbox.jpg" class="ampliar lightbox">clique para ampliar</a>
    </div>
    <div class="product-box-2">
     <a href="img/produtos/1-lightbox.jpg" class="lightbox"><img src="img/produtos/1.jpg" alt=""></a>
     <p class="legend">>> Vero mlkshk velit, freegan ullamco commodo put a bird on it cred synth kogi, Vero mlkshk velit, freegan ullamco commodo put a bird on it cred synth kogi.</p>
     <a href="img/produtos/1-lightbox.jpg" class="ampliar lightbox">clique para ampliar</a>
    </div>

而且很多时候都需要它。然后我尝试在 .legend 上设置一个很好的效果,使用 CSS 设置"display:none"和 Jquery:

    $('.product-box-2 a').mouseenter(
    function(){
    $('.legend').fadeIn();
});
$('.product-box-2').mouseleave(
    function(){
    $('.legend').fadeOut();
});

但是我有相同的类,因此,当我将鼠标放在一些 .product-box-2 上时,所有图例都会出现......而且我不知道如何只选择我所在的 .product-box-2 a 中的 .legend。

如果你想看到它的实际效果,就在这里!

通过将内部选择器元素作为上下文,将内部选择器的作用域限制为发生事件的元素。 请参阅文档,了解接受上下文的签名。

$('.product-box-2 a').mouseenter(
   function(){
    $('.legend',$(this).closest('div')).fadeIn();
});
$('.product-box-2').mouseleave(
    function(){
    $('.legend',this).fadeOut();
});

您也可以尝试.children([Selector])

$('.product-box-2 a').mouseenter(
    function(){
    $(this).children('.legend').fadeIn();
});
$('.product-box-2').mouseleave(
    function(){
    $(this).children('.legend').fadeOut();
});

http://api.jquery.com/children/

你需要的是

$(this).find('.legend').fadeIn();

在这种情况下,$(this) 是指触发事件的元素,.find()仅在其子元素中查找。