jQuery parent(),parents()和nearest()函数之间的区别

时间:2012-02-08 12:22:12

标签: jquery

我一直在使用jQuery。我想使用parent()选择器。我还想出了closest()选择器。找不到它们之间的任何区别。有没有?如果有,那是什么?

parent()parents()closest()之间有什么区别?

6 个答案:

答案 0 :(得分:180)

来自http://api.jquery.com/closest/

  

.parents() .closest()方法类似,因为它们都是   遍历DOM树。但两者之间存在差异   微妙,重要:

     

.closest()

     
      
  • 从当前元素开始
  •   
  • 向上移动DOM树,直到找到所提供的匹配项   选择
  •   
  • 返回的jQuery对象包含零个或一个元素
  •   
     

<强> 。家长()

     
      
  • 从父元素开始
  •   
  • 将DOM树移动到文档的根元素,添加每个元素   祖先元素到临时集合;然后过滤它   基于选择器的集合(如果提供了一个
  • )   
  • 返回的jQuery对象包含零个,一个或多个元素
  •   
     

<强> .parent()

     
      
  • 给定一个表示一组DOM元素的jQuery对象,   .parent()方法允许我们通过这些父母进行搜索   DOM树中的元素并从中构造一个新的jQuery对象   匹配元素。
  •   
     

注意: .parents()和.parent()方法类似,只是   后者只在DOM树上运行一个级别。也,   $(“html”)。parent()方法返回包含文档的集合   $(“html”)。parents()返回一个空集。

以下是相关主题:

答案 1 :(得分:155)

  

closest()选择与选择器匹配的第一个元素   来自DOM树。从当前元素开始并向上移动。

     

parent()选择一个元素(单层向上)DOM树。

     

parents()方法与parent()类似,但选择所有方法   匹配DOM树的元素。从父元素开始并向上移动。

答案 2 :(得分:13)

两者之间的差异虽然微妙,但却很重要:

  

.closest()

     
      
  • 从当前元素开始
  •   
  • 向上移动DOM树,直到找到所提供选择器的匹配项
  •   
  • 返回的jQuery对象包含零个或一个元素
  •   
     

.parents()

     
      
  • 从父元素开始
  •   
  • 将DOM树移动到文档的根元素,将每个祖先元素添加到临时集合中;然后,如果提供了一个选择器,则根据选择器过滤该集合
  •   
  • 返回的jQuery对象包含零个,一个或多个元素
  •   

来自jQuery docs

答案 3 :(得分:1)

$(this).closest('div')$(this).parents('div').eq(0)

之间存在差异

基本上closest从当前元素开始匹配元素,而parents开始匹配父元素(当前元素上一级)的元素

See http://jsfiddle.net/imrankabir/c1jhocre/1/

答案 4 :(得分:0)

parent()方法返回所选元素的直接父元素。此方法仅遍历DOM树的单个级别。

parents()方法允许我们搜索DOM树中这些元素的祖先。从给定的选择器开始并向上移动。

The **.parents()** and **.parent()** methods are almost similar, except that the latter only travels a single level up the DOM tree. Also, **$( "html" ).parent()** method returns a set containing document whereas **$( "html" ).parents()** returns an empty set.

[closest()][3]method returns the first ancestor of the selected element.An ancestor is a parent, grandparent, great-grandparent, and so on.

This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

According to docs:

**closest()** method is similar to **parents()**, in that they both traverse up the DOM tree. The differences are as follows:

**closest()**

Begins with the current element
Travels up the DOM tree and returns the first (single) ancestor that matches the passed expression
The returned jQuery object contains zero or one element

**parents()**

Begins with the parent element
Travels up the DOM tree and returns all ancestors that matches the passed expression
The returned jQuery object contains zero or more than one element





 

答案 5 :(得分:-1)

$(this).closest('div')$(this).parents('div').eq(0)相同。