Jquery 如何获取包含最少子级的父级?

Jquery 如何获取包含最少子级的父级?,jquery,dom,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

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

<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>
  • 马特
  • 约翰
  • 标记
  • 罗杰
  • 账单
  • 劳拉
  • 米里亚姆
  • 迪伦
  • 哈利
对于理解和检索“容器”(容器中的子容器最少),最优化的方法是什么?

var$el=$('ul.containers:first');
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.
$('ul.containers')。每个(函数(){ if($(this.children().length<$(this.next('ul.containers').children().length){ $el=$(此项); } }); 控制台日志($el)//$el现在是孩子最少的父母。
或稍短一点的单行版本,如果:

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.
var$el=$('ul.containers:first');
$('ul.containers')。每个(函数(){
$el=$(this).children().length<$(this).next('ul.containers').children().length?$(this):$el;
});
控制台日志($el)//$el现在是孩子最少的父母。

避免不必要的闭包和使用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
var containers=$('.containers');
var-least_children=null;
var\u container=null;
对于(var i=0;i

在JSFIDLE上:

非常好,您完全理解我的“检索”部分。但是,如果有两个以上的父容器,会发生什么?它迭代每个UL元素并比较子元素的数量。数字不是问题。不过,使用jQuery的
每个
函数的速度不如本地循环快。也可以考虑在jQuery元素中包装
这个
,以计数子元素,而不是直接检查数字wasteful@Codemonkey:您如何直接计算孩子数?@MoinZaman:关于您的问题,您可以使用
element.childElementCount
。检查我的answer@MoinZaman:我的解决方案快了10倍:我认为你的解决方案肯定快了。如果你在寻找最快的解决方案,你检查了错误的答案。我的解决方案大约快10倍。这里是一个性能比较:@Codemonkey,是的,你是对的,但是我在jQuery中寻找最快的解决方案,而不是在原生JS中。我的解决方案还使用jQuery选择元素,你可以轻松地将结果元素包装到jQuery对象中,以获得与接受答案相同的结果。当解决方案包装在函数中时,如果函数内部使用本机JavaScript或慢速jQuery函数,会有什么不同?