簡體   English   中英

jQuery選擇最接近元素的子元素

[英]jQuery select child of closest element

基本上,我希望能夠從子級別4的div中選擇父級別的div。 我的應用程序沒有此類,否則我只選擇level2 :)

<div class="level1">
  <div class="level2">
    <div class="level3">
      <div class="level4"></div>
    </div>
  </div>
  <div class="level2"> <!-- this is hidden -->
    <div class="level3">
      <div id="start" class="level4"></div>
    </div>
  </div>
</div>

我從$('#start') ,搜索可見的第一個父級,但是我沒有找到一種方法來返回該父級的子級。 從父級開始,在父級中搜索$('#start')似乎很浪費。

$('#start').closest(':visible') // returns level1
$('#start').closest(':visible').first() // returns the first level2. I can't just use second because the number of level2s can change.
$('#start').closest(':visible').children().each(function(){ /* do some search to check it contains `$('#start')` }) // seems very wasteful.

看我想說的另一種方式是: 從中間開始,找到外部(可見元素),然后向內移動一個元素。

這個怎么樣:-

$('#start').parentsUntil(':visible').last();

這將為您提供所有隱藏的父div,直到其可見的parent和last()將給出被隱藏的最外面的父。 last不是位置上的選擇器,它是集合中的last()。

您需要.has()方法

說明:將匹配元素集減少為具有與選擇器或DOM元素匹配的后代的元素。

$('#start').closest(':visible').children().has('#start');

例如參見小提琴。

使用.filter()

$('#start').closest(':visible').children().filter(':first-child')

.find()也非常適合選擇幾乎所有內容。

您說這些類不存在...為什么不添加它們? 這將使思想更容易找到。 類名不需要關聯實際的樣式。

var allLevel4 = $('#start').closest(':visible').find('.level4');
var firstLevel4 = $('#start').closest(':visible').find('.level4')[0];
var secondLevel4 = $('#start').closest(':visible').find('.level4')[1]; //also, #start

暫無
暫無

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

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