jQuery 使用 event.target 获取元素

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

Using event.target to get element

jquery

提问by user1184100

I'm basically trying to get the target element from event.target and if not equal process. How can i get the below thing to work ?

我基本上是试图从 event.target 获取目标元素,如果不是平等的过程。我怎样才能让下面的东西工作?

$(document).ready(function(){
   $(document).click(function(event) {

       if(event.target!='#contents') {  //If clicked element is not div #contents show alert .. //How can i achieve this ?
         alert("..");
       }

    });
});

回答by Nicola Peluchetti

use

   //If clicked element id is not contents 
   if(event.target.id !== 'contents') {  
     alert("..");
   }

EDIT - if the structure is that of your comment use:

编辑 - 如果结构是您的评论使用的结构:

  if($(event.target).closest('div#contents').length === 0){
    alert('there is no div with id === "contents" in the ancestors of the clicked li');
   }

EDIT 2 - explanation of my code. If you have this markup

编辑 2 - 解释我的代码。如果你有这个标记

<div id="contents"><ul><li>Item1</li><li>Item2</li></ul></div>

this code means

这段代码意味着

//event.target is a DOM element, so wrap it into a jQuery object
$(event.target)
        .closest('div#contents')//find a div element going up the dom tree. 
                                //This method returns a jQuery collection that it's 
                                //empty if the div is not found
        .length //the collection has a length 
                //property that is equal to the number of found elements