简体   繁体   English

在JQuery事件中查找父元素

[英]Find parent element in JQuery event

I've added a click event as follows and would like to check if the target has a specific parent. 我已经添加了一个click事件,如下所示,并希望检查目标是否具有特定的父级。

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

How can this be done? 如何才能做到这一点?

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() ? 我不确定你为什么要在文档上设置click handler,也许是在寻找事件委托和.on()

I believe this also works.. AFAIK jQuery events use the the literal element instead of a jQuery object when calling events. 我相信这也有效.AFAIK jQuery事件在调用事件时使用文字元素而不是jQuery对象。 Basically this should be your normal DOM element with normal JavaScript properties. 基本上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. 注意:有时使用'self'作为变量是坏/导致与某些库冲突所以我使用$ elf。 The $ in $elf is not special, like a jQuery convention or anything. $ elf中的$并不特别,就像jQuery约定或任何东西。

$(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 }
});

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. 这将为您提供对调用事件的元素的jQuery对象的引用。 You could use this same approach and see if the parent is "#parent", something like this: 您可以使用相同的方法,看看父级是否是“#parent”,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM