假设我有以下的标记:
<div class="parent">
<div class="child">
<div class="grand-child">
我希望从 .grand-child
开始获取 .parent
。我可以选择以下两种方法之一:
$('.grand-child').parent().parent();
$('.grand-child').closest('.parent');
总的来说,closest()
似乎是一种更好的方法,因为:
- 只有一个函数
- 它与
.grand-child
和.parent
之间的其他 div 无关
具体来说,由于上述优点 #2 的优势,如果我要更改我的标记为
<div class="parent">
<div class="child">
<div class="nanny">
<div class="grand-child">
然后我需要添加一个额外的parent()
,但是closest()
仍然可以正常工作。
那么你为什么会选择parent()
或者closest()
呢?
.parent()
方法。 - Regentparent()
和closest()
函数时,有许多差异和需求。它取决于您实际需要什么。请查看它们之间的区别此处。 - Avinash Babuclosest
。但是,如果你只想要上一级,例如,那么parent
就会非常有用。parent
的优点在于你不需要标签来找到它。这完全取决于你的需求。 - lurkerclosest()
对于特定目标更有效,尤其是当不确定它们离多远时。 - charlietflclosest
实际上是检查元素本身。http://jsfiddle.net/tarabyte/A7ngQ/ - Yury Tarabanko