blur和click事件的先后顺序问题

这两个同时用会有冲突。懒得翻译了,需要的自己看哈。

以下摘自stackoverflow。

I have an input field, where I try to make autocomplete suggestion. Code looks like

<input type="text" id="myinput">
<div id="myresults"></div>

On input's blur() event I want to hide results' div:

$("#myinput").live('blur',function(){
     $("#myresults").hide();
});

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.

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();
});

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.

How can I set up click() event before blur()?

 

Solution 1

Listen to mousedown instead of click.

The mousedown and blur events occur one after another when you press the mouse button, but click only occurs when you release it.

Solution 2

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();
});

转载于:https://www.cnblogs.com/xiaoweiy/p/4961450.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值