2012-04-05 72 views
8

我基本上试图从event.target获取目标元素,如果不是相等的过程。 我怎样才能让下面的东西工作?使用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(".."); 
     } 

    }); 
}); 

回答

12

使用

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

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

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

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

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

这个代码意味着

//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 
+1

+1 @ user1184100:'event.target'是一个对象,而不是字符串。它的**'id' **是一个字符串。 – 2012-04-05 09:33:36

+0

当我做一个console.log(event.target);它返回div的div ..但不是div id #contents所以上面的代码将无法正常工作:( 结构是这样的

  • Item1
  • Item2
user1184100 2012-04-05 09:34:53

+0

@ user1184100我编辑我的答案检查它是否适用于您并在您的问题中发布您的标记 – 2012-04-05 09:38:14