2012-07-22 50 views
2

我們有兩個彼此相鄰的容器,裏面有容器。如何獲得包含最少孩子的父母?

<ul class="containers"> 
    <li>Matt</li> 
    <li>John</li> 
    <li>Mark</li> 
</ul> 
<ul class="containers"> 
    <li>Roger</li> 
    <li>Bill</li> 
    <li>Lara</li> 
    <li>Miriam</li> 
    <li>Dylan</li> 
    <li>Harry</li> 
</ul> 

什麼是最優化的方法,理解和檢索的「容器」,裏面坐了至少孩子嗎?

+1

如果你正在尋找的* *最快的解決方案,你已經檢查了錯誤的答案。我的解決方案快了大約10倍。這是一個性能比較:http://jsperf.com/comparing-two-child-element-counters – Hubro 2012-07-22 01:38:48

+0

@Codemonkey,是的,你是對的,但是我正在尋找jQuery中最快的解決方案,而不是本地JS。 – 2012-07-22 11:32:19

+0

我的解決方案也使用jQuery來選擇元素,並且可以輕鬆地將生成的元素包裝到jQuery對象中,以獲得與接受的答案相同的結果。它的區別是什麼,當解決方案包裝在一個函數中時,如果函數使用本地JavaScript或緩慢的jQuery函數? – Hubro 2012-07-22 14:34:46

回答

3
var $el = $('ul.containers:first'); 

$('ul.containers').each(function(){ 
    if($(this).children().length < $(this).next('ul.containers').children().length){ 
    $el = $(this); 
    } 
}); 

console.log($el); //$el is now the parent with the least children. 

或稍短版本如果一行:

var $el = $('ul.containers:first'); 

$('ul.containers').each(function(){ 
    $el = $(this).children().length < $(this).next('ul.containers').children().length ? $(this) : $el ; 
}); 

console.log($el); //$el is now the parent with the least children. 
+0

非常好,你完全理解我的「檢索」部分。 – 2012-07-22 00:56:59

+0

但是,如果有兩個以上的父容器,會發生什麼情況? – 2012-07-22 01:00:04

+0

它遍歷**每個** UL元素並比較孩子的數量。數量不是問題。儘管使用jQuery的'each'函數並不像本地循環那麼快。另外,將'this'包裝進jQuery元素來計算孩子數量而不是直接檢查數字可能會被認爲是浪費 – Hubro 2012-07-22 01:01:57

2

避免不必要的關閉和使用for循環,這應該很好地執行迭代。我很確定這個解決方案比Moin Zaman的代碼更快。不是很漂亮 - 取決於你是否需要最高性能。

var containers = $('.containers'); 
var least_children = null; 
var smallest_container = null; 

for(var i = 0; i < containers.length; i++) 
{ 
    var container = containers[i]; 

    if(least_children === null) 
    { 
     least_children = container.childElementCount; 
     smallest_container = container; 
    } 
    else if(container.childElementCount < least_children) 
    { 
     least_children = container.childElementCount; 
     smallest_container = container; 
    } 
}; 

// smallest_container now contains the UL with the least children as a 
// HTMLElement 

上的jsfiddle:http://jsfiddle.net/BXnnL/3/

+0

如果您有時間可以比較兩者:http://jsperf.com/ – 2012-07-22 01:20:10

+0

@MoinZaman:我的解決方案速度提高了10倍:http://jsperf.com/comparing-two-child -element-counters – Hubro 2012-07-22 01:37:21

+1

我認爲你的解決方案肯定更快。 – 2012-07-22 01:41:34