如何获得包含最少孩子的父母?

时间:2012-07-22 00:41:37

标签: jquery dom

我们有两个彼此相邻的容器,里面有容器。

<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>

最强优化方法是什么,用于理解和检索“容器”,其中包含最少的子项?

2 个答案:

答案 0 :(得分: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.

或稍短版本的单行if:

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.

答案 1 :(得分: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/