如何使用“this”作为选择器的一部分

How do I use "this" as a part of a selector?

本文关键字:选择器 一部分 何使用 this      更新时间:2023-09-26

我试着这样做:

$(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)
});

我需要将其作为"each"函数运行,因为我想稍后输入条件。

试试这个

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

从文档

jQuery( selector [, context] )

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

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)
});

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

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

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

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

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

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