Javascript 在 JQuery 事件中查找父元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12200277/
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-08-23 07:23:38  来源:igfitidea点击:

Find parent element in JQuery event

javascriptjquery

提问by ihkawiss

I've added a click event as follows and would like to check if the target has a specific parent.

我添加了一个点击事件,如下所示,并想检查目标是否有特定的父级。

$(document).click(function(event){
    // Check here if target has specific parent for example -> #parent
});

How can this be done?

如何才能做到这一点?

回答by complex857

There's a .parent()dom traversal method for this.

有一个.parent()dom 遍历方法。

according to Pointy's crystal ball, you probably want to do something like this:

根据 Pointy 的水晶球,你可能想做这样的事情:

$(document).click(function(event) {
  if ($(event.target).parents('.selector').length > 0) {
  }
});

I'm not sure why are you set click handler on document, maybe looking for event delegation and the .on()?

我不确定你为什么要在文档上设置点击处理程序,也许是在寻找事件委托和.on()

回答by Garet Claborn

I believe this also works.. AFAIK jQuery events use the the literal element instead of a jQuery object when calling events. Basically thisshould be your normal DOM element with normal JavaScript properties.

我相信这也有效.. AFAIK jQuery 事件在调用事件时使用文字元素而不是 jQuery 对象。基本上this应该是具有普通 JavaScript 属性的普通 DOM 元素。

$(document).click(function(event)
{
   myparent = $(this.parentNode); //jquery obj
   parent = $(this.parentNode)[0]; //plain DOM obj

   myself = $(this); //jquery obj;
   $elf = this; //plain DOM obj
});

Note: sometimes using 'self' as a variable is bad/causes conflicts with certain libraries so i used $elf. The $ in $elf is not special, like a jQuery convention or anything.

注意:有时使用“self”作为变量是不好的/会导致与某些库发生冲突,所以我使用了 $elf。$elf 中的 $ 并不特殊,就像 jQuery 约定或任何东西。

回答by Gabe

$(document).click(function(event){
    var $parent = $(this).parent();

     // test parent examples 
    if($parent.hasClass('someclass')) { // do something }

    if($parent.prop('id') == 'someid')) { // do something }

    // or checking if this is a decendant of any parent

    var $closest = $(this).closest('someclass');

    if($closest.length > 0 ) { // do something }

    $closest = $(this).closest('#someid'); 

    if($closest.length > 0 ) { // do something }
});

回答by Andrew Trice

I have reliably used this in the past:

我过去可靠地使用过这个:

var target = $( event.target )

This will give you a reference to the jQuery object for the element that had the event invoked. You could use this same approach and see if the parent is "#parent", something like this:

这将为您提供对调用该事件的元素的 jQuery 对象的引用。您可以使用相同的方法并查看父级是否为“#parent”,如下所示:

var target = $( event.target )
if (target.parent().attr('id') == "#parent") {
    //do something
}