jQuery,找到父项 [英] JQuery, find parent

查看:88
本文介绍了jQuery,找到父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<ul><li><div><div><span id="thisid"></span></div></div></li></ul>

$('#thisid').parent('li');

那显然是行不通的,但是我该如何获取li元素呢?我不想使用:

that obviously doesn't work, but how do I grab the li element? I don't want to use:

$('#this').parent().parent().parent();

我不想使用它,因为有可能只有一个div元素,而不是两个.在这种情况下,我将获取ul元素而不是li元素.

I don't want to use it, because it can happen that there is just one div element, instead of two. In this case I would grab the ul element instead of the li element.

推荐答案

$('#thisid').parents('li');
//                 ^ plural!

请注意,如果只希望祖先中的第一个<li>元素,则应使用closest():

Note that if you only want the first <li> element in the ancestry, you should use closest():

$('#thisid').closest('li');

// `closest()` is equivalent to (but performs better than)
$('#thisid').parents('li').eq(0);
$('#thisid').parents('li').first();

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