簡體   English   中英

這是查詢元素及其子元素的最佳方法嗎?

[英]Is this the best way to query an element and its children?

我正在嘗試查詢元素及其子元素以查找以特定字符串開頭的ID。

var foundIDs = containerElement.find('[id^=something]').andSelf().filter('id^=something');

find()方法僅搜索后代,所以我想嘗試andSelf() 但是, andSelf()沒有選擇器。 這意味着無論容器元素是否與查找查詢匹配,都將包括該容器元素,然后,如果容器元素畢竟不匹配,我必須對其執行輔助filter()來刪除該容器元素。

我試圖把andSelf() find() ,但它似乎沒有容器元素拿起入堆棧。

containerElement.andSelf().find('[id^=something]');

有什么更好的方法可以實現我的目標嗎?

剛剛離開我的頭頂(未經測試):

var foundIDs = containerElement
                     .filter('id^=something')
                     .add(containerElement.find('id^=something'));

這並沒有比您的初衷更加有效,但是我認為它稍微干凈了一點。

containerElement.find('*').andSelf().filter('[id^=something]');

我知道您已經接受了答案,但是無論如何我都會把這個扔掉。

var foundIDs = containerElement.wrap('<div>')             // Wrap
                               .parent()                  // Traverse up
                               .find('[id^=something]');  // Perform find

containerElement.unwrap();  // DOM is untouched

因為您在功能完成之前就展開了containerElement包裝,所以DOM保持不變(以防您想知道)。

我用livequery插件驗證了它,它從未檢測到新的div

如果您記錄了foundID的ID(或其他值),您將看到頂層是您的containerElement(假設它符合.find()條件)。

console.log( foundIDs.attr('id') );  // Log the ID of the root element.

編輯:

關於測試,我對只有兩個嵌套元素的containerElement在兩個版本上執行了1,000次迭代循環。

我僅在Mac上的Safari中進行過測試。

可接受的答案快了大約7倍。

如果添加100個嵌套元素,則差距縮小到不到2倍。

這是麻煩。 如果containerElement不匹配,則兩個版本均返回0個元素。 我不確定為什么會這樣。

這個性能比我的其他答案更好,但是您失去了接受的答案所提供的鏈接能力。

    // Do a typical find.
var found = containerElement.find('[class^=something]');

    // Test the containerElement directly,
    //    and push it into the 'found' object if it matches.
if( containerElement.is('[class^=something]') ) found.push(containerElement);

暫無
暫無

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

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