javascript parentUntil() 是最好用的函数吗?查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7743442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:08:35  来源:igfitidea点击:

Is parentsUntil() the best function to use? Jquery

javascriptjquery

提问by maxp

Given the html:

鉴于 html:

     <div class="a">
        <div class="b">
           <div class="c">
             <div class="d">
             </div>
           </div>
          <div class="d">
          </div>
        </div>
     </div>

Im interested in the selecting the parent element with class aapplied to it when any element with the class 'd' is clicked.

a当单击具有类“d”的任何元素时,我对选择应用了类的父元素感兴趣。

I have the following javascript / jQuery, but it seems very messy. Is there a neater way?

我有以下 javascript/jQuery,但看起来很乱。有没有更简洁的方法?

<script>
   $('.d').click(function(){
      var elementA =  $(this).parentsUntil('.a').last().parent();    
   })
</script>

回答by SLaks

You want$(this).closest('.a').

$(this).closest('.a')

回答by keeganwatkins

you can also do:

你也可以这样做:

$(".d").click(function() {
    // parents() will walk up through parent nodes. If you
    // pass a selector, the set will be filtered. If not,
    // you get the full list of parent elements.
    var elementA = $(this).parents(".a");
});

docs here.

文档在这里

hope that helps! cheers.

希望有帮助!干杯。