2011-12-14 48 views
2

我有以下功能隱藏秒的一定格,當我點擊任何地方在頁面上:隱藏DIV的任何地方點擊時,但另一個DIV瓦特/ jQuery的

$("html").click(function() { 
    $(".myDiv1").addClass("hidden"); 
}); 

我想一個例外添加到該功能。如果點擊另一個專區內,忽略這個隱藏......對我來說,只有這樣,才能選擇第二功能是選擇一個獨特的元素withing它:

$(".nyOtherDiv").parent() 

如何結合這些?或者我應該把它作爲一個單獨的函數添加到下面來覆蓋第一個函數?

回答

3

您可以使用event.target來查看單擊了哪個元素。如果是你想要排除的那個div,那麼不要添加該類,否則添加該類。

var exclude_div = $(".nyOtherDiv").parent(); 
$(document).click(function(e){ 
    if(!exclude_div.is(e.target)) // if target div is not the one you want to exclude then add the class hidden 
     $(".myDiv1").addClass("hidden"); 

}); 

這是fiddle

0
$(document).not('div').click(function() { 
    //everywhere in the document that is NOT a div 
    $(".myDiv1").addClass("hidden"); 
}); 
+0

不,我需要精確到我提到的那個。 ) – santa 2011-12-14 22:38:34