【问题标题】:Get nth-child and act on it :jQuery获取 nth-child 并对其采取行动:jQuery
【发布时间】:2011-12-13 05:54:11
【问题描述】:

下面的代码只作用于最后一个子元素,它会触发所有其他子元素的函数。

$('.streetdog').hide();
$('.cat').mouseenter(function(){
    var $catVal = $(".cat").index(this);
    $('.streetdog:nth-child('+$catVal+')').show();
});

您可以在jsfiddle 上查看演示。 基本上我正在尝试触发特定循环的子元素并悬停.cat

【问题讨论】:

    标签: jquery selector css-selectors


    【解决方案1】:

    使用:eq 而不是:nth-child。由于.eq():eq 更有效,请改用.eq()

    $('.streetdog').hide();
    $('.cat').mouseenter(function(){
        var $catVal = $(".cat").index(this);
        $('.streetdog').eq($catVal).show();
    });
    

    小提琴:http://jsfiddle.net/rkM8N/1/

    $('.streetdog').eq() 创建一个包含所有类名等于streetdog 的元素的集合。然后,.eq(n) 返回此集合中的第 n 个元素。

    $('.streetdog:nth-child(' + $catVal + ')') 选择一个.streetdog 元素,它是其父元素的$catValth 子元素。因此,仅当$catVal 等于 2 时才会显示元素。

    【讨论】:

    • 谢谢,但我想知道:eq:nth-child之间的基本区别是什么,我搜索了一些论坛,他们都说两者几乎相同。
    • @tunetosuraj - 请参阅nth-child 的 jQuery 文档(我已将相关引用复制到我的答案中) - api.jquery.com/nth-child-selector
    【解决方案2】:

    已经给出了一个非常好的答案,但作为替代方案,如果您的 HTML 结构不会改变,您可以使用 parent 到达父级 div,并使用 next 获取.streetdog元素:

    $(".streetdog").hide();
    $(".cat").mouseenter(function() {
        $(this).parent().next().show(); 
    });
    

    这是working example

    eq 有效,而nth-child 无效的原因由jQuery docs 解释:

    :nth-child(n) 伪类很容易与 :eq(n) 混淆,甚至 尽管两者可能会导致完全不同的匹配元素。 使用 :nth-child(n),所有孩子都被计算在内,不管他们是什么 是,并且仅当指定的元素与 附加到伪类的选择器。使用 :eq(n) 仅选择器 附在伪类上也算,不限于子级 任何其他元素,并选择第 (n+1) 个(n 从 0 开始)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2017-08-11
      • 2012-11-19
      • 1970-01-01
      相关资源
      最近更新 更多