2012-07-22 51 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