簡體   English   中英

jQuery根據匹配父類的類選擇器查找子節點

[英]jQuery find child based on class selector matching parents

我試圖使用jquery .find()方法找到特定節點的后代。 我注意到.find()根據樹中當前節點上方父項的屬性不匹配元素。 第一個find返回0個元素,但第二個find返回我正在搜索的元素。 我的問題是,這是否是find方法允許的選擇器模式的限制,並且找到唯一具有此限制的jquery函數? 我希望這兩個都返回相同的元素。 另外,是否有另一種jquery方法可以更簡潔地完成與第二​​種方法相同的操作。 這是我正在嘗試做的簡化示例,我無法刪除.find('.input-group')因為這是我的函數的輸入。

 $(document).find('.input-group').find('.form-group .form-control') $(document).find('.input-group').find('.form-control').filter('.form-group .form-control') 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"> <input type="checkbox" aria-label="CVV Disabled" value=""> </span> <input id="vtCvv" name="vtCvv" type="password" class="form-control" required="true" data-bv-field="vtCvv"> </div> </div> </body> </html> 

.find()查找元素的后代。 你試圖找到一個父母,然后是一個后代。

您可以找到.input-group ,然后使用.closest()向后遍歷DOM到“最近的” .form-group ,然后您可以向下導航到.form-control如下所示:

$(document).find('.input-group').closest('.form-group').find(".form-control")

或者您可以使用.parent()回溯到.form-group如下所示:

$(document).find('.input-group').parent().find(".form-control")

我更喜歡.closest()因為如果要在.input-groupform-group之間添加另一個元素,那么父元素會有所不同,但是.closest仍然可以工作。

$('.form-group .input-group').find('.form-control');

暫無
暫無

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

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