获取父级/祖先 UL

Get the parent/ancestor UL

本文关键字:祖先 UL 获取      更新时间:2023-09-26

>我有一个看起来像

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

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

如果 UL 是父元素,this.parentNode工作,但如果它是祖先之一,我必须使用this.parentNode.parentNode取决于中间有多少父元素......

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

既然你已经把问题标记为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;
}

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

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

对于性能,

你也可以像下面这样使用jquery,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建议采用这种方式。

这是小提琴。

通常你会使用这样的.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 -元素)处停止。

如果ul.xa的直接父级,请使用以下命令:

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

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