简体   繁体   English

如何使用JQuery从子节点访问父节点?

[英]How to access to a parent node from a child node using JQuery?

I have the following markup: 我有以下标记:

<div class"cA" >
   <div class="c..">
       <div class="cZ" >
       </div>
   </div>
</div>

How can I from the div which has the class cZ get the div which has class cA , knowing that the number of divs between then is not specific. 我如何从具有类cZ的div获得具有类cA的div,知道当时之间的div数不是特定的。

var $parent = $('.cZ').parents('.cA');

As others have said, parents() will walk the parent chain and accumulate the elements that match the specified selector. 正如其他人所说, parents()将遍历父链并累积与指定选择器匹配的元素。 However, if more than one parent element matches the selector (in your case, if more than one parent <div> exposes the cA class), then the jQuery object that is returned will contain more than one element. 但是,如果多个父元素与选择器匹配(在您的情况下,如果多个父<div>公开cA类),则返回的jQuery对象将包含多个元素。

If that behavior isn't what you want, consider using closest() instead. 如果该行为不是您想要的,请考虑使用nearest()

Just use the .parents() method. 只需使用.parents()方法即可。 It should return what you're looking for. 它应该返回你想要的东西。

Look in to Jquery Tree Traversal API. 查看Jquery Tree Traversal API。 The one that help you in this case is .parents() 在这种情况下帮助你的是.parents()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM