如何获取jQuery中元素的第n级父级? [英] How do I get the n-th level parent of an element in jQuery?

查看:76
本文介绍了如何获取jQuery中元素的第n级父级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当我想获取元素的3级父级时,必须写$('#element').parent().parent().parent()对此是否有更优化的方法?

When I want to get, for example, the 3rd level parent of the element I must write $('#element').parent().parent().parent() Is there a more optimal method for this?

推荐答案

由于 parents()返回从最接近外部元素开始排序的祖先元素,您可以将其链接到 eq():

Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():

$('#element').parents().eq(0);  // "Father".
$('#element').parents().eq(2);  // "Great-grandfather".

这篇关于如何获取jQuery中元素的第n级父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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