且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

哪个 JQuery 选择器会排除与给定选择器匹配的父项的项目?

更新时间:2023-11-20 22:53:10

事情的真相是,jQuery 根本没有一个特别优雅的方式来做你想做的事.虽然混乱的答案确实有效,但您必须想知道复杂的选择器(与复杂网页中的选择器一样慢)是否值得您拥有更详细但更快的过滤器功能.这并不是什么大不了的事,我个人只是厌倦了特别长、复杂的选择器,但我可以避免它.

The truth of the matter is that jQuery simply does not have a particularly elegant way to do what you want. While chaos' answer does work, you have to wonder whether the complicated selector (that would be about as slow as a selector can be in a complicated webpage) is worth it over the more verbose but faster filter function you have. This is not really that big of a deal, I am just personally weary of particularly long, convoluted selectors when I can avoid it.

另一种选择是创建自己的选择器,因为 jQuery 很棒:

A different option is to create your own selector, since jQuery is awesome:

jQuery.expr[':'].parents = function(a,i,m){
    return jQuery(a).parents(m[3]).length < 1;
};

$('.foo,.bar').filter(':parents(.baz)');

expr 映射是 Sizzle 选择器引擎的一部分,可以在此处找到文档:嘶嘶作响的自定义伪选择器

The expr map is part of the Sizzle selector engine and documentation can be found here: Sizzle Custom Pseudo-Selectors