2011-09-21 103 views
0

我有一個搜索結果div,如果用戶在其外部任何地方點擊,我想隱藏它。它不是搜索標準div的孩子。 我遇到的問題是.show()似乎並沒有被解僱。我會認爲.hide()只會在最初點擊搜索按鈕後觸發。很明顯,當搜索結果div關閉時,我會將.unbind()事件。在元素被綁定之前綁定事件

有點難住這一個,所以任何幫助將不勝感激。

下面是一些示例代碼。

function search(){ 
    $('#criteria').bind('click',function(){$('#results').hide();}); 
    $('#results').show(); 
    $('#results').html('some html from ajax call'); 
} 

<div id=criteria> 
    <input id=criteria1 /><input id=criteria2 /><input id=criteria3 /> 
    <!-- a whole page of input elements and a ajax lookup --> 
    <input type=text id=lookup /><input type="button" onclick="search()" value="search" /> 
</div> 
<div id=results></div> 
+0

嘗試添加隱藏回調的東西* *大像'body'或「文件」。 – Yoshi

+0

@Yoshi但當我點擊結果div時不會發生這種情況?我需要這個保持開放,以便可以選擇多個項目。 –

+0

請參閱:http://jsfiddle.net/WCLem/1/希望它有幫助。 – Yoshi

回答

0

如果我理解正確的話,你需要這樣的

<script> 
$(document).bind('click',function(){$('#results').hide();}); 

function search(e){  
    $('#results').show(); 
    $('#results').html('some html from ajax call'); 
    e.cancelBubble = true; 
} 
</script> 

<div id=criteria> 
<input id=criteria1 /><input id=criteria2 /><input id=criteria3 /> 
<!-- a whole page of input elements and a ajax lookup --> 
<input type=text id=lookup /><input type="button" onclick="search(event)" value="search" /> 

+0

不錯!剛剛添加到.unbind中,因此當結果div隱藏時它不會觸發; ('click',function(){$('#results')。hide(); $(document).unbind('click');}); –