jQuery选择祖先 [英] jQuery select ancestor

查看:282
本文介绍了jQuery选择祖先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用jQuery选择元素的祖先?

Is is possible to use jQuery to select an ancestor of an element?

标记:

<div id="ancestor-1">
    <div>
        <a href="#" class="click-me">Click me</a>
    </div>
</div>
<div id="ancestor-2">
    <div>
        <a href="#" class="click-me">Click me</a>
    </div>
</div>

脚本:

$(".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)
});

closest() 用于最接近的匹配元素(祖先或自身) ).

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

parents()closest()之间的区别是细微但重要的. closest()将返回当前元素(如果匹配);否则将返回当前元素. parents()返回仅祖先​​.许多人不希望返回当前元素. closest()也只返回一个元素; parents()返回所有匹配的元素.

The difference between parents() and closest() is subtle but important. closest() will return the current element if it's a match; parents() returns only ancestors. You many not want the possibility of returning the current element. closest() also only returns one element; parents() returns all matching elements.

这篇关于jQuery选择祖先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆