jQuery选择祖先

有可能使用jQuery来选择元素的祖先吗?

标记:

  

脚本:

 $(".click-me").click(function(){ // var ancestorId = ???; alert(ancestorId) }); 

尝试使用parent()作为直接父元素。

 $(".click-me").click(function() { var ancestor = $(this).parent(); alert(ancestor) }); 

或者parents()用于所有匹配的祖先元素。

 $(".click-me").click(function() { var ancestors = $(this).parents(".some-ancestor"); alert(ancestors) }); 

或者对于第一个最接近的匹配元素(祖先或自我)的最近()。

 $(".click-me").click(function() { var ancestor = $(this).closest(".some-ancestor"); alert(ancestor) }); 

parents()closest()之间的区别很微妙但很重要。 如果匹配, closest()将返回当前元素; parents() 返回祖先 。 你们许多人不希望有可能返回当前元素。 closest()也只返回一个元素; parents()返回所有匹配的元素。

你的意思是这样的?

 $('.click-me').click(function() { var $theAncestor = $(this).closest('#ancestor-1'); } 

这将搜索所有祖先,直到找到匹配项。

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

编辑:

杰罗姆,你的问题可以用几种方式解释。 这说明了jQuery的强大function和灵活性。

请考虑以下事项。

首先,回答你的问题,是的,可以使用jQuery来选择元素的祖先。

我想我们可以假设你知道jQuery能够通过以下方式选择任何元素,无论是祖先还是后代:

 $('#myElement') 

给出click-me示例,如果您想要返回一个元素的所有祖先的集合,请使用:

 $(this).parents() 

要么

 $(this).parents(selector) 

但请注意,这将遍历返回all的所有祖先,或者在给出选择器时匹配所有匹配的祖先。

如果您希望返回直接父级,请使用:

 $(this).parent() 

如果您知道您需要哪个祖先,请使用:

 $(this).closest(selector) 

但请注意,它只会返回第一个匹配项,如果当前元素(this)匹配,它将返回该匹配项。

我希望这有帮助。

尝试结合使用parents()或nearest(),或者使用选择器来确定哪个祖先应该匹配。 例如,找到最近的具有id的祖先div。

 $('.click-me').click( function() { var ancestorId = $(this).closest('div[id]'); alert(ancestorId); }); 

你在找parent()吗? 用于父选择器的jQuery Doc 。 如果您的方案不同,请说明您的预期输出是多少。

http://api.jquery.com/parent/和http://api.jquery.com/parents/

 $(".click-me").click(function(){ var ancestorId = $(this).parent().parent(); alert(ancestorId) }); 

将返回带有ID的div

这真的取决于你想要达到的目标。 您想搜索所有祖先,无论使用哪个类? 或者你想搜索祖先的所有元素并具有某些类(在你的情况下是祖先-x)?

如果你想循环遍历任何祖先,只需使用.parent() (这是一个很好的例子,如何遍历所有元素)或.parents()你可以使用如下:

 $(".click-me").click(function(){ var parentElements = $(this).parents().map(function () { return this.tagName; }) // whatever else you want to do with it }); 

可能最好的方法是使用.parents()直到你获得具有某个id或class的元素。 这真的取决于你想做什么。

Interesting Posts