Jquery获取嵌套元素的数量

时间:2022-09-09 14:30:16

Consider a dynamic dropdown-menu. Because of creating this code server side I don't know the exact number of li situated in div 'sub'.Example HTML output:

考虑动态下拉菜单。由于创建了这个代码服务器端,我不知道div'sub'中的li的确切数量。示例HTML输出:

<li>
    <a href="#">Videos</a>
        <div id="sub">
            <ul>
                <li><a href="#">Main</a></li>   
                <li><a href="#">Acting</a></li>                                     
                <li><a href="#">Animals</a></li>
            </ul>
        </div>
   </li>

The following script should give the number of li in the in div id="sub"

以下脚本应该在div id =“sub”中给出li的数量

$(function() {
        $('.tabMenu li a').click(function() {
        currentLink = $(this);
       //Get number of children elements
       alert(currentLink.children().size());
});

Any help will be greatly appreciated.

任何帮助将不胜感激。

3 个解决方案

#1


1  

   alert(currentLink.parent().find('li').size());

#2


1  

First: where is your .tabMenu in your code?

第一:您的代码中的.tabMenu在哪里?

Try with:

试试:

.length;

Working solution

$('.tabMenu li a').click(function() {
    currentLink = $(this);
    alert(currentLink.parents('ul').children('li').length); 
});

#3


1  

What you need to do is get the parent container of the li element, then see how many children it has:

你需要做的是获取li元素的父容器,然后查看它有多少个子容器:

$(function() {
    $('.tabMenu li a').click(function() {
   // Get the parent ul of the current link
   var currentLinkParent = $(this).parents("ul:first");

   alert(currentLinkParent.children().size() );

});

#1


1  

   alert(currentLink.parent().find('li').size());

#2


1  

First: where is your .tabMenu in your code?

第一:您的代码中的.tabMenu在哪里?

Try with:

试试:

.length;

Working solution

$('.tabMenu li a').click(function() {
    currentLink = $(this);
    alert(currentLink.parents('ul').children('li').length); 
});

#3


1  

What you need to do is get the parent container of the li element, then see how many children it has:

你需要做的是获取li元素的父容器,然后查看它有多少个子容器:

$(function() {
    $('.tabMenu li a').click(function() {
   // Get the parent ul of the current link
   var currentLinkParent = $(this).parents("ul:first");

   alert(currentLinkParent.children().size() );

});