使用jQuery来获取元素的后代,这些元素的后代不是具有特定CSS类的容器的子代 [英] Use jQuery to get descendants of an element that are not children of a container with a certain CSS class

查看:89
本文介绍了使用jQuery来获取元素的后代,这些元素的后代不是具有特定CSS类的容器的子代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一种情况下,我需要选择某个元素的所有后代,但排除那些是与我的选择器所作用的容器的CSS类相等的容器的子代.

I have a situation in which i need to select all descendants of a certain element, but exclude those that are children of a container that equals the CSS class of the container i run my selector on.

非常复杂的描述.

<div class="container">
   <div class="element"></div>
   <div class="element"></div>
   <div class="element"></div>
   <div class="element">
       <div class="container">
           <div class="element"></div>
           <div class="element"></div>
           <div class="element"></div>
       </div>
   </div>

在最外面的DIV上运行jQuery .find('.element')将获得所有DIV,即使是第二个容器中的DIV.这就是我要避免的事情.

Running a jQuery .find('.element') on the outermost DIV will get me all the DIVs, even the ones inside the second container. That is what i try to avoid.

在这种情况下,有没有一种快速,简单的jQuery选择器解决方案?

Is there a quick and simple jQuery selector solution for this case?

推荐答案

我认为您要使用的是不是选择器.像这样.

I think what you want to use is the not selector. Like this..

$(".container").not(".container .container")

或者,您可以使用 children 选择器,使子级更深.这将排除嵌套的div.

Alternately, you could use the children selector, to get the children from one level deep. Which would exlclude the nested divs.

更明确一点,我想您将在使用'find'之后要使用not选择器.像这样:

To be a little more explicit, I think you'll want to use the not selector after you use the 'find'. Like this:

$(".container").find(".element").not($(".container .container .element"))

您可以不传递函数,因此可以让该函数查看每个元素匹配项的父元素,以查看它是否嵌套在具有相同类的元素中.

You can pass a function to not, so you could have that function look at the parents of each element match to see if it is nested inside of an element with the same class.

http://jsfiddle.net/QXfs2/6/

removeIfNested = function(index) {
    // this is the corrent DOM element
    var $this = $(this),
        return_value = false;

    $.each($this.attr('class').split(/\s+/), function(index) {
        if ($this.parents("." + this).length > 0) {
            return_value = default_value || true;
        }
    });

    return return_value;
}


$(".container").find(".element").not(removeIfNested);

如果您可以将一个类添加到嵌套容器中,那将是理想的,那就是:

If you could add a class to the nested container, that would be ideal, then it's just:

$(".container").find(".element").not($(".nested .element"))

假设您将嵌套"类添加到内部容器div中.

Assuming you added the class "nested", to your inner container div.

这篇关于使用jQuery来获取元素的后代,这些元素的后代不是具有特定CSS类的容器的子代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆