jQuery选择祖先(jQuery select ancestor)

92 IT屋

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

Markup:

<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>

Script:

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

Try parent() for the immediate parent element.

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

Or parents() for all matching ancestor elements.

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

Or closest() for the first closest matching element (either an ancestor or self).

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

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选择元素的祖先?



标记:



 < div id = ancestor-1> 
< div>
< a href =# class = click-me>点击我< / a>
< / div>
< / div>
< div id = ancestor-2>
< div>
< a href =# class = click-me>点击我< / a>
< / div>
< / div>


脚本:



 < code> $(。click-me)。click(function(){
// var ancestorId = ???;
alert(ancestorId)
});

解决方案

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



  $(。click-me)。click(function(){
var祖先= $(this).parent ();
alert(祖先
});


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



< pre> $(。click-me)。click(function(){
var ancestors = $(this).parents(。some-ancestor);
警报(祖先
});


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



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


parents()和< code> closest()很微妙但很重要。 closest()将返回当前匹配的元素; parents()返回仅祖先​​。许多人不希望返回当前元素。 closest()也只返回一个元素; parents()返回所有匹配的元素。


本文地址:IT屋 » jQuery选择祖先