获得父/祖先UL

时间:2012-05-03 12:43:00

标签: javascript jquery

我有一个看起来像

的HTML标记
<ul>
  ...

    <li>
      <ul class="x">
        ...
        <a href="#"...

如何从链接上的点击事件中获取父ul.x元素?

如果UL是父元素,则

this.parentNode有效,但如果它是祖先之一,我必须使用this.parentNode.parentNode,具体取决于父元素之间的数量...

我可以以某种方式获得第一个UL父母吗?

5 个答案:

答案 0 :(得分:4)

因为您已将问题标记为jQuery:

$(this).closest("ul"); //Get the first ancestor `ul`
$(this).closest("ul.x"); //Get the first ancestor `ul` with class `x`

或者,没有jQuery(因为你的例子似乎没有使用jQuery):

var node = this;
while(node.tagName !== "UL") {
    node = node.parentNode;
}

答案 1 :(得分:2)

使用closest()。这将获得与您提供的选择器匹配的最近的祖先。

$(function(){
    $('a').on('click',function(){         //handler of your <a>
        var ulx = $(this).closest('ul.x'); //find the closest ancestor <ul> with class "x"
    });
});

答案 2 :(得分:1)

如果ul.xa的直接父级,请使用此代码:

    $('a').on('click',function(){
        var ul = $(this).parent('ul.x');
    });

    $('a').on('click',function(){
       var ul = $(this).closest('ul.x');
    });

答案 3 :(得分:1)

通常你会使用.closest()之类的:

$('a').click(function(){    
   var ul = $(this).closest('ul.x'); //or just closest('ul') in case you only used the x for demo purposes
});

这会出现在DOM树上并在第一场比赛(你的ul.x - 元素)处停止。

答案 4 :(得分:1)

为了表现,

您也可以使用下面的jquery on,jquery eventObject也有一个名为delegateTarget的属性,这可能对您的情况有用。

$('ul.x').on('click', 'a', function(e){


    //e.delegateTarget is the parent ul of the clicked a tag
    //e.target.id is the clicked a tag

    alert(e.delegateTarget.id); 
    alert(e.target.id);

});​

<强> HTML:

 <ul id='a' class="x">
      <li><a id='1' href="#">A</a></li>
      <li><a id='2' href="#">B</a></li>
      <li><a id='3' href="#">C</a></li>
 </ul>

 <ul id='b' class="x">
      <li><a id='11' href="#">1</a></li>
      <li><a id='21' href="#">2</a></li>
      <li><a id='31' href="#">3</a></li>
 </ul>​

就性能而言,您不会在所有a标记上绑定事件。 jQuery以这种方式建议。

这是fiddle