如何使用jQuery从子级到父级查找元素计数? [英] How to find element count from child to parent with jquery?

查看:124
本文介绍了如何使用jQuery从子级到父级查找元素计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,我需要计算元素的嵌套级别. 问题在于父元素可以包含多个子元素,而子元素可以具有自己的子元素.

I have a slight issue where i need to count nest level of elements. Problem is that parent element can hold multiple child elements and child elements can have their own child elements.

请查看我要从何处开始计数(标有我从这里开始"的文字).

Please see from where i want to start count (marked with text "I start here").

HTML:

<div class="main_set">
    <div class="child_set">
        <div class="child_set">
            <div class="child_set">I start here!</div>
        </div>
        <div class="child_set"></div>
    </div>
    <div class="child_set">
        <div class="child_set"></div>    
    </div>
</div>

我已经尝试了一些事情来计算3.
例如我最后一次尝试:

I have tried couple things to get count 3.
For example my last attempt:

$(this).closest('.main_set').find('.child_set');

这个数字显然会返回6,并计算所有子集.

This one obviously returns 6 tho counting all child_sets.

如何仅从嵌套开始就计算从起始位置到main_setchild_set个元素.所以基本上在我的示例中,如何获得计数3?

How to count child_set elements from start place to main_set taking into account only nesting. So basically in my example how to get count 3?

推荐答案

您可以使用 parents()this中查找所有父母(具有特殊选择器);对于长度,您必须为当前长度添加一个.

You can use parents() from this to find all parents (with a special selector); for the length you have to add one for the current.

alert($(this).parents('.child_set').length + 1);

另请参见此示例.

这篇关于如何使用jQuery从子级到父级查找元素计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆