使用jquery查找两个元素之间的节点数? [英] find number of nodes between two elements with jquery?

查看:159
本文介绍了使用jquery查找两个元素之间的节点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找出快速完成(看似)简单任务的方法时遇到了一些麻烦。假设我有以下html:

 < ul> 
< li> One< / li>
< li>两个< / li>
< li id ='parent'>
< ul>
< li>三< / li>
< li>
< ul>
< li>四< / li>
< li id ='child'> Five< / li>
< / ul>
< / li>
< li>六< / li>
< / ul>
< / li>
< / ul>

并且有以下两个元素:

  var child = $(#child); 
var parent = $(#parent);

在这个例子中,很清楚:

  child.parent()的父()的父()的父()。; 

与'parent'的节点相同。但是我正在遍历的列表是可变大小的,所以我需要找到一种方法来找出我需要经历多少'.parent()才能到达那个父节点。我总是知道孩子和父母在哪里,我只是不知道它们之间有多少'层'。



是否有任何内置的jQuery方法可以做某事像这样,或者我最好的选择一个获取父节点的递归函数,检查父节点是否是我想要的节点,如果没有调用它的父节点?



编辑:我可能没有足够清楚地解释自己。我的问题是没有得到父母,我的问题是找出孩子和父母之间有多少节点。在上面的示例中,child和parent之间有3个节点。这是我需要找到的数据。

解决方案

如果您只想找到父母,请执行以下操作:

  child.parents(#parent); 

这比做起来容易:



<$ p $ 。p> child.parent()的父()的父();

还是有其他原因你需要知道这个号码吗?



一个简单的循环可以做到:

  var node = child [0]; 
var depth = 0;
while(node.id!='parent'){
node = node.parentNode;
depth ++;
}


I'm having a little trouble figuring out a fast way to accomplish a (seemingly) simple task. Say I have the following html:

<ul>
  <li>One</li>
  <li>Two</li>
  <li id='parent'>
    <ul>
      <li>Three</li>
      <li>
        <ul>
          <li>Four</li>
          <li id='child'>Five</li>
        </ul>
      </li>
      <li>Six</li>
    </ul>
  </li>
</ul>

And have the following two elements:

var child = $("#child");
var parent = $("#parent");

In this example, it's clear that:

child.parent().parent().parent().parent();

will be the same node as 'parent'. But the list I'm traversing is variable size, so I need to find a way to find out how many '.parent()'s I'll need to go through to get to that parent node. I always know where child and parent are, I just don't know how many 'layers' there are in between.

Is there any built in jQuery method to do something like this, or is my best bet a recursive function that gets the parent, checks if the parent is my desired node, and if not calls itself on its parent?

Edit: I may not have explained myself clearly enough. My problem isn't getting TO the parent, my problem is finding out how many nodes are between the child and parent. In my example above, there are 3 nodes in between child and parent. That's the data I need to find.

解决方案

If you just want to get to the parent, do this:

child.parents("#parent");

That's easier than doing:

child.parent().parent().parent();

Or is there some other reason you need to know the number?

A simple loop could do it:

var node = child[0];
var depth = 0;
while (node.id != 'parent') {
  node = node.parentNode;
  depth++;
}

这篇关于使用jquery查找两个元素之间的节点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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