jQuery:fire click()before blur()事件 [英] jQuery: fire click() before blur() event
问题描述
美好的一天!
我有一个输入字段,我尝试自动完成建议。代码看起来像
I have an input field, where I try to make autocomplete suggestion. Code looks like
<input type="text" id="myinput">
<div id="myresults"></div>
在输入的 blur()
隐藏结果div:
On input's blur()
event I want to hide results' div:
$("#myinput").live('blur',function(){
$("#myresults").hide();
});
当我写一些东西到我的输入我发送请求到服务器,并获得json响应,解析为ul - > li结构,并将这个ul放到我的 #myresults
div。
When I write something into my input I send request to server and get json response, parse it into ul->li structure and put this ul to my #myresults
div.
当我点击这个解析的li元素,我想设置值从li到输入和隐藏 #myresults
div
When I click to this parsed li element I want to set value from li to input and hide #myresults
div
$("#myresults ul li").live('click',function(){
$("#myinput").val($(this).html());
$("#myresults").hide();
});
一切都很好,但当我点击我的li blur
事件在 click()
之前触发,输入的值不会获得li的html。
Everything is going good, but when I click to my li blur()
event fires before click()
and input's value don't get li's html.
如何在 blur()之前设置
click()
c $ c>
How can I set up click()
event before blur()
?
推荐答案
解决方案1
code> mousedown 而不是点击
。
mousedown
和 blur
事件一个接一个地发生,当您按下鼠标按钮,但单击$ c $
The mousedown
and blur
events occur one after another when you press the mouse button, but click
only occurs when you release it.
您可以 preventDefault ()在
mousedown
,以阻止下拉列表从偷焦。轻微的优点是,当鼠标按钮被释放时,将选择该值,这是本机选择组件的工作原理。 JSFiddle
You can preventDefault()
in mousedown
to block the dropdown from stealing focus. The slight advantage is that the value will be selected when the mouse button is released, which is how native select components work. JSFiddle
$('input').on('focus', function() {
$('ul').show();
}).on('blur', function() {
$('ul').hide();
});
$('ul').on('mousedown', function(event) {
event.preventDefault();
}).on('click', 'li', function() {
$('input').val(this.textContent).blur();
});
这篇关于jQuery:fire click()before blur()事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!