筛选出的父项的 jQuery 后代仍在集合中

  • 本文关键字:集合 后代 jQuery 筛选 jquery
  • 更新时间 :
  • 英文 :


目标:.Third 类内的 p 标签上没有红色轮廓。

下面的自包含示例,或此处的jsfiddle:http://jsfiddle.net/WJVBm/

迫切地期待着授予绿色复选标记...提前感谢任何帮助!

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        var myDivs = $('div');
        var myFilteredDivs = myDivs.filter(function(){
            return $(this).closest('.third').length == 0;
        });
        var myFilteredParagraphs = myFilteredDivs.find('p'); // why does this find paragraphs in divs that have already been filtered out of the collection?
        myDivs.css('border', '1px solid #CCC');
        myFilteredDivs.css('border', '1px solid blue');
        myFilteredParagraphs.css('border', '1px solid red'); // paragraphs inside of divs that should not exist in the collection are still being outlined by a red border
    });
    </script>
    <style type="text/css">
        div { float: left; padding: 20px; margin: 5px; }
    </style>
</head>
<body>
    <div class="first">
        <p>first</p>
        <div class="second">
            <p>second</p>
            <div class="third">
                <p>third</p>
            </div>
        </div>
        <div class="second">
            <p>second2</p>
        </div>
        <div class="third">
            <p>third2</p>
        </div>
    </div>
</body>
</html>

试试这个 http://jsfiddle.net/3JALD/

它可能可以改进,但它似乎可以满足您的需求。

所有段落都是为myFilteredParagraphs找到的,因为div.firstmyFilteredDivs的一部分,find()得到了div.first后代的所有p

似乎是一个非常简单的,也许是显而易见的修复:

http://jsfiddle.net/WJVBm/13/

var myFilteredParagraphs = myFilteredDivs.find('> p'); // why does this find paragraphs in divs that have already been filtered out of the collection?

使用直接子选择器>

这能满足您的需求吗?

最新更新