2012-08-15 22 views
0

目標: .third類中的p標籤上的紅色輪廓。下面過濾出來的父母的jQuery後代仍在收藏中

自給例子,或這裏的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> 
+1

這是因爲它們也是其他非過濾元素的後代。根據你的實際標記,你可能會用'children()'而不是'find()'離開。 – 2012-08-15 14:45:32

+1

問題是'myDivs'包含每個比賽中的每個div和它的嵌套子節點。 添加'console.log(myDivs);',你可以在輸出中看到它。 – Nope 2012-08-15 14:47:07

回答

1

試試這個http://jsfiddle.net/3JALD/

它大概可以改善,但它似乎做你的需要。

所有段落被發現的myFilteredParagraphs因爲div.first是的myFilteredDivsfind()得到所有的p S中的從div.first後代的一部分。

1

似乎是一個非常簡單的,也許顯而易見的解決辦法:

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? 

使用直接子選擇>

這是否你在尋找什麼?