内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我有一个输入字段,我尝试提出自动填充建议。代码看起来像
<input type="text" id="myinput">
<div id="myresults"></div>
在输入的blur()
事件我想隐藏结果'div:
$("#myinput").live('blur',function(){
$("#myresults").hide();
});
当我写入我的输入的东西,我发送请求到服务器,并得到JSON响应,解析成ul->li结构,把这个UL到我的#myresults
。
当我点击这个解析的li元素时,我想从li设置值来输入和隐藏#myresults
div
$("#myresults ul li").live('click',function(){
$("#myinput").val($(this).html());
$("#myresults").hide();
});
一切都很顺利,但是当我点击我的li blur()
事件之前触发click()
,输入的值不会得到li的html。
我如何设置click()
事件blur()
?
$(document).on('blur', "#myinput", hideResult); $(document).on('mousedown', "#myresults ul li", function(){ $(document).off('blur', "#myinput", hideResult); //unbind the handler before updating value $("#myinput").val($(this).html()).blur(); //make sure it does not have focus anymore hideResult(); $(document).on('blur', "#myinput", hideResult); //rebind the handler if needed }); function hideResult() { $("#myresults").hide(); }