jQuery - 选择除所有内容

jQuery - Select everything but

本文关键字:选择 jQuery      更新时间:2023-09-26

我想使用 jQuery 来选择页面上除某个div之外的所有内容。我的问题与此答案类似,但该解决方案仅选择div,我想选择所有内容

在这个例子中,小提琴,我想选择所有没有,或者不是带有"孩子"类的元素的后代的所有内容。因此,单击"孙子"和"孩子"不应显示日志条目,但单击"父"或图像会。

该页面将具有非常复杂的结构,因此这样的事情是不可行的。

你可以试试 not 选择器

$('body *').not('.kids, .kids *');

或者,如果您尝试注册事件处理程序,则

$(document).on('click', ':not(.kids, .kids *)', function(){
})

使用此代码,此代码排除.kids类的.kids元素和内部元素

$('body').click(function(e) {
    if(!$(e.target).closest('.kids').length){
      console.log(e.target);
    }
});

演示

在 jquery 中使用 e.currentTarget

$("#parent").not($('.kids')).click(function(e) {
    console.log(e.currentTarget);
});