Javascript 在激发元素之前绑定元素上的事件

Javascript 在激发元素之前绑定元素上的事件,javascript,jquery,event-handling,bind,Javascript,Jquery,Event Handling,Bind,我有一个搜索结果div,如果用户单击它之外的任何地方,我想将其隐藏。它不是搜索条件div的子项。 我遇到的问题是.show()似乎根本没有启动。我原以为.hide()只在初次单击搜索按钮后才会触发。很明显,当search results div关闭时,I.unbind()会触发事件 这件事有点难办,所以任何帮助都将不胜感激 下面是一些示例代码 function search(){ $('#criteria').bind('click',function(){$('#results').h

我有一个搜索结果div,如果用户单击它之外的任何地方,我想将其隐藏。它不是搜索条件div的子项。 我遇到的问题是.show()似乎根本没有启动。我原以为.hide()只在初次单击搜索按钮后才会触发。很明显,当search results div关闭时,I.unbind()会触发事件

这件事有点难办,所以任何帮助都将不胜感激

下面是一些示例代码

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


如果我理解正确,您需要这样的东西

<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" />

$(document).bind('click',function(){$('#results').hide();});
函数搜索(e){
$(“#结果”).show();
$('#results').html('来自ajax调用的一些html');
e、 取消气泡=真;
}

尝试将隐藏回调添加到更大的对象,如
body
document
@Yoshi,但当我在results div中单击时,不会触发吗?我需要它保持打开状态,以便可以选择多个项目。请参阅:希望它有帮助。在您的代码示例中,
show
已成功执行,但在下一刻,
单击(启动
seacrch()
函数)将从
INPUT[type=button]
弹出到
DIV\chrises
。因此,
DIV#条件
单击
事件被激发并隐藏#result.Nice!刚刚在.unbind中添加,所以当results div被隐藏时它不会触发$(document).bind('click',function(){$('#results').hide();$(document).unbind('click');});
<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" />