2012-04-05 67 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