jQuery,找到父项 [英] JQuery, find parent
本文介绍了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();
- http://api.jquery.com/closest/
- http://api.jquery.com/parents/
- http://api.jquery.com/closest/
- http://api.jquery.com/parents/
这篇关于jQuery,找到父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文