JQuery - 如何计算选择器选择的元素数量?

时间:2021-05-16 14:30:41

I am using $().fadeOut() to fade items out in a list ( < li> < /li>). When the list is empty I wish to hide a parent object.

我使用$()。fadeOut()来淡出列表中的项目(

  • )。当列表为空时我希望隐藏父对象。

  • I plan on doing this by checking in my trigger event that fades the list if the count of the objects is 0 then hide the parent element. I can use the fadeOut callback to remove the elements if necessary.

    我打算通过检查触发器事件来完成此操作,如果对象的计数为0则忽略列表然后隐藏父元素。如果需要,我可以使用fadeOut回调删除元素。

    The to the point question: How do I select li tags inside a ul and then get the total count of them using jquery?

    关键问题:如何在ul中选择li标签,然后使用jquery获取它们的总数?

    3 个解决方案

    #1


    27  

    Like this:

    $('ul > li').length
    

    A more elegant way to do it would be to write

    更优雅的方式就是写作

    $('ul:empty').fadeOut();
    

    If the ul is not empty, the selector won't match anything, and the code will do nothing.

    如果ul不为空,则选择器将不匹配任何内容,代码将不执行任何操作。

    You may need to write

    你可能需要写

    $('.SomeContainer:has(ul:empty)').fadeOut();
    

    #2


    11  

    use .length

    $('ul li').length // gives you back all li's in your ul
    $('ul > li').length // give just the first children li's
    

    so in order to hide your parent you can use it this way:

    所以为了隐藏你的父母,你可以这样使用它:

    elements = $('ul > li')
    
    if (elements.length) {
       elements.fadeOut()
    }else{
       elements.parent().fadeOut()
    }
    

    #3


    5  

    Simply use .length against the jQuery collection.

    只需对jQuery集合使用.length。

    var $elements = $('ul#myUlElement').children('li');
    alert($elements.length)
    

    #1


    27  

    Like this:

    $('ul > li').length
    

    A more elegant way to do it would be to write

    更优雅的方式就是写作

    $('ul:empty').fadeOut();
    

    If the ul is not empty, the selector won't match anything, and the code will do nothing.

    如果ul不为空,则选择器将不匹配任何内容,代码将不执行任何操作。

    You may need to write

    你可能需要写

    $('.SomeContainer:has(ul:empty)').fadeOut();
    

    #2


    11  

    use .length

    $('ul li').length // gives you back all li's in your ul
    $('ul > li').length // give just the first children li's
    

    so in order to hide your parent you can use it this way:

    所以为了隐藏你的父母,你可以这样使用它:

    elements = $('ul > li')
    
    if (elements.length) {
       elements.fadeOut()
    }else{
       elements.parent().fadeOut()
    }
    

    #3


    5  

    Simply use .length against the jQuery collection.

    只需对jQuery集合使用.length。

    var $elements = $('ul#myUlElement').children('li');
    alert($elements.length)