2

我试着这样做:

$(this + ' li:not(:nth-last-child(2)):not(:last-child)').hide()

完整代码示例:

$('.comments').each(function(){
    $(this + ' li:not(:nth-last-child(2)):not(:last-child)').hide()
    var template = $('#expand').html();
    $(this).prepend(template)
});

我需要将它作为“每个”函数运行,因为我想稍后输入一个条件。

4

3 回答 3

4

试试这个

$('li:not(:nth-last-child(2)):not(:last-child)', this).hide();

来自文档

jQuery( 选择器 [, 上下文] )

选择器 - 包含选择器表达式的字符串

context - 用作上下文的 DOM 元素、文档或 jQuery

所以你可以this用作上下文参数:

$('.comments').each(function(){
    $('li:not(:nth-last-child(2)):not(:last-child)', this).hide()
    var template = $('#expand').html();
    $(this).prepend(template)
});
于 2012-06-23T14:06:08.900 回答
2

如果你想找到所有li:not(:nth-last-child(2)):not(:last-child)inside this,你可以使用find()

$(this).find('li:not(:nth-last-child(2)):not(:last-child)').hide();

另外值得注意的是,如果您知道要查找的元素只会是一级深度,那么您应该使用children()而不是find().

于 2012-06-23T14:06:03.487 回答
0

这是一个对象而不是字符串,您可以将其他字符串附加到该对象上以构建您需要的选择器。

只需使用find()来遍历代码:

$('.comments').each(function(){
    $(this).find('li').not(':nth-last-child(2)').not(':last-child').hide();
    var template = $('#expand').html();
    $(this).prepend(template);
});
于 2012-06-23T14:07:59.663 回答