2011-09-21 104 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');}); –