扩展jQuery $(this)

6

如何将选择器仅从$(this)扩展到其子元素,或者说,扩展到其他任何元素?我的意思是,如何正确地使用$(this)连接它们?

例如:

$("li.nav").each(function() {
    $(this AND children of this, or this AND it's siblings).something();
});

不好意思,如果这个问题已经有答案了,我找不到它。

1个回答

8
你可以使用 andSelf 来实现这个功能:
$(this).children().andSelf().something();

你也可以使用.end来取消当前链上的最后一个过滤操作。因此,如果你想要子元素和同级元素,你也可以实现:

$(this)
    .children()    // children of "this"
    .end()         // now we're back to "this"
    .siblings()    // siblings of "this"
    .andSelf()     // and "this" itself
    .something();

哈哈,这是迄今为止最快的。谢谢! - cincplug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接