【问题标题】:How to target the nth-child of $(this)如何定位 $(this) 的第 n 个孩子
【发布时间】:2016-08-26 17:33:56
【问题描述】:

我试图在悬停时定位元素的第 n 个子元素。

我的html是这个......

<div class="parent">
     <div class="child1"></div>
     <div class="child2"></div>
     <div class="child3"></div>
</div>

目前,.child3display:none,但在悬停.parent 时,我想对所有内容应用不透明度,并显示.child3 且没有不透明度。

目前为止

$(".parent").hover(function() {
       $(this:nth-child(3)).show();
});

我需要使用$(this),因为我的标记在显示不同产品的页面上重复出现。所以我只想针对我悬停的特定产品。

我是不是找错树了?

对不起,如果这是一个愚蠢的问题,我确切地知道我想做什么,但不能完全执行它!

【问题讨论】:

标签: jquery css hover


【解决方案1】:

你可以

$(this).children(':nth-child(3)').show();

演示:Fiddle

【讨论】:

    【解决方案2】:

    你可以使用find

    $(this).find('> :nth-child(3)').show(); 
    

    Fiddle

    JSPerf 全部三个选项。

    顺便说一下,如果您有除 div 之外的其他元素作为目标元素的兄弟元素,并且您想显式选择第三个 div,请使用nth-of-type。在这种情况下,nth-child 将失败,因为它也会考虑任何其他类型的孩子,如果它出现在第 3 个之前,则第 3 个 div 不会被选中。

    $(this).find('> div:nth-of-type(3)').show(); 
    

    【讨论】:

      【解决方案3】:

      您也可以使用this

      $(".parent").hover(function() {
      
          $('> div:nth-child(3)', this).toggle();
      });
      

      【讨论】:

      • div:nth-child(3) 实际上没有任何区别,如果你想专门选择 div 则需要使用div:nth-of-type(3)。看到这个失败的jsfiddle.net/EBDmk。您可以从头开始删除 div。
      • 是的!你也可以使用 $(':nth-child(3)', this).toggle();但是如果孩子里面还有其他兄弟姐妹呢。
      • 不!这也会选择嵌套的。所以('&gt; :nth-child(3)', this) 就足够了,但是对于特定的类型选择需要使用selector:nth-of-type(3)
      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 2021-12-03
      • 2011-01-17
      • 2013-01-21
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2016-07-08
      相关资源
      最近更新 更多