如何使用jQuery在html中获取div的祖父母的祖父母 [英] How to get the grandparent of the grandparent of a div in html using jQuery

查看:213
本文介绍了如何使用jQuery在html中获取div的祖父母的祖父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来获得父母的父母...比如5次?



所以不要用这个:

()。parent()。parent()。parent()
$ b $

  code> 

我可以这样使用:

  $(本).goBacktoNthParent(5); 

是否可能?

解决使用:eq()选择器

:eq()选择器允许您在匹配的集合的从零开始的索引处定位元素...

  $(this).parents(':eq(4)')

注意:使用父级选择器

因为选择器是基于零的,所以我们给它一个而不是定位的数量。



DEMO: http://jsfiddle.net/pmMFv/






使用 .eq()方法



.eq ()方法实际上与其选择对象相同,因此您可以将该元素定位到匹配的集合的从零开始索引...

  $(this).parents()。eq(4)

注意:使用父级选择器



http:// jsfiddle。 net / pmMFv / 2 /




使用 parentNode 在循环中为了获得最佳性能,我们可以使用 .parentNode 属性的元素,然后在循环中运行它,每次更新最新的父变量...

  var el =这个,我= 5; 
while(i--&&(el = el.parentNode));

$(el)

DEMO: http://jsfiddle.net/pmMFv/1/ p>

Is there a better way to get the parent of the parent of the parent... like 5 times?

So Instead of using this:

$(this).parent().parent().parent().parent().parent()

I could use something like this:

$(this).goBacktoNthParent(5);

Is it possible?

解决方案

Using the :eq() selector

The :eq() selector allows you to target the element at the zero-based index of the set that was matched...

$(this).parents(':eq(4)')

Note: use parent(s) selector

Because the selector is zero based, we gave it one less than the number targeted.

DEMO: http://jsfiddle.net/pmMFv/


Using the .eq() method

The .eq() method is effectively the same as its selector counterpart, allowing you to target the element at the zero-based index of the set that was matched...

$(this).parents().eq(4)

Note: use parent(s) selector

DEMO: http://jsfiddle.net/pmMFv/2/


Using parentNode in a loop

For greatest performance, we could use the .parentNode property of the element, and run it in a loop, updating a variable with the newest parent each time...

var el = this, i = 5;
while(i-- && (el = el.parentNode));

$(el)

DEMO: http://jsfiddle.net/pmMFv/1/

这篇关于如何使用jQuery在html中获取div的祖父母的祖父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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