2010-05-28 163 views
6

我有form裏面的東西一個div像Jquery-隱藏的div

<form> 
<div> 
showing some information here 
</div> 

<div id="idshow" style="display:none"> 
information here 
</div> 

</form> 

我是在一些按鈕單擊事件內格(idshow)人口信息。當我在外部div(idshow)之外點擊時我想要什麼,它應該隱藏。就像我點擊菜單,然後菜單顯示,當我點擊菜單外面它隱藏。 我需要利用一切手段,jQuery的

回答

11
$(document).click(function(event) { 
    var target = $(event.target); 

    // Check to see if the target is the div. 
    if (!target.is("div#idshow")) { 
    $("div#idshow").hide(); 
    // Prevent default event -- may not need this, try to see 
    return(false); 
    } 
}); 
3

你可以做你想做的是這樣的:

$(document).click(function() { 
    $("#idshow").hide(); 
}); 
$("#idshow").click(function(e) { 
    e.stopPropagation(); 
}); 

這裏發生的當您單擊是,該click事件一路向上冒泡到document,如果到達那裏我們隱藏了<div>。當你點擊裏面那<div>雖然,你可以通過使用event.stopPropagation() ...阻止氣泡達到document ...所以.hide()不會觸發,簡短和簡單:)