簡體   English   中英

jQuery-查找具有給定數量的同級元素

[英]JQuery - Find element that has a given number of siblings

我需要能夠搜索JQuery對象的每個后代,並返回在該層次結構級別上可能具有給定數目的成員的所有同級兄弟的集合,從最遠的后代對象開始,然后進行備份。

因此,給出一些HTML:

<div class="search-me">
  <div> <!-- DON'T FIND THIS -->
    <p>FIND ME</p>
    <p>FIND ME</p>
    <p>FIND ME</p>
  </div>
  <div> <!-- DON'T FIND THIS -->
    <span></span>
    <span></span>
  </div>
  <div> <!-- DON'T FIND THIS -->
    <div>FIND ME</div>
    <div>FIND ME</div>
    <div>FIND ME</div>
  </div>
</div>

我需要以下偽代碼,以返回標有“查找我”的項目,而無其他...

$('.search-me').findGroupWithSize(3);

另外,請注意,有三個div包含<p><span><div>標記,不應其返回。 因此,它應返回一組最低級別的元素的集合,這些元素的同級元素總數為給定的數量。

下面的示例從您發布的HTML中查找3組。

 var siblingsGroupTarget = 3; var foundIndex = 0; var elementArray = []; $(".search-me").find("*").each(function(index){ // Conditions var hasChilds = $(this).children().length; var hasSiblings = $(this).siblings().length; var itsSiblings = $(this).siblings(); var itsSiblingsHasChilds = itsSiblings.children().length; console.log( $(this)[0].tagName+": "+$(this).siblings().length ); if( hasChilds == 0 && ( hasSiblings == siblingsGroupTarget-1 && itsSiblingsHasChilds == 0 ) ){ elementArray.push( $(this) ); } }); elementArray.reverse(); for(i=0;i<elementArray.length;i++){ foundIndex++; elementArray[i].addClass("FOUND").append(" I was found #"+foundIndex); }; 
 .FOUND{ border:3px solid red; width:12em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="search-me"> <div> <!-- DON'T FIND THIS --> <p>FIND ME</p> <p>FIND ME</p> <p>FIND ME</p> </div> <div> <!-- DON'T FIND THIS --> <span></span> <span></span> </div> <div> <!-- DON'T FIND THIS --> <div>FIND ME</div> <div>FIND ME</div> <div>FIND ME <ul> <!-- DON'T FIND THIS --> <li>FIND ME</li> <li>FIND ME</li> <li>FIND ME</li> </ul> </div> </div> </div> 

您可以使用傳遞給jQuery()選擇器".search-me > *"來獲取.search-me元素的直接后代,使用.toArray()將jQuery對象轉換為數組,使用Array.prototype.reverse()來反轉集合的元素, .filter()檢查子元素.length是否為N ,用選擇器"> *"jQuery()數組方法包裝起來,以返回匹配元素的子元素

 const N = 3; let res = $("> *", $(".search-me > *").toArray().reverse() .filter(function(el) {return $("> *", el).length === N})); console.log(res); res.css("color", "purple") 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div class="search-me"> <div> <!-- DON'T FIND THIS --> <p>FIND ME</p> <p>FIND ME</p> <p>FIND ME</p> </div> <div> <!-- DON'T FIND THIS --> <span>DON'T FIND ME</span> <span>DON'T FIND ME</span> </div> <div> <!-- DON'T FIND THIS --> <div>FIND ME</div> <div>FIND ME</div> <div>FIND ME</div> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM