<选择>使用键盘时未触发更改事件 [英] <select> change event not fired when using keyboard

查看:64
本文介绍了<选择>使用键盘时未触发更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsfiddle.net/rFEER/

<select id="users">
<option value="1">jack</option>
<option value="2">brill</option>
<option value="3">antony</option>
</select>​

js:

$("#users").change(function(){
    alert($(this).val());
})​

为什么使用(keyup/keydown)直到单击鼠标时才触发更改事件

why change event not fired when using (keyup/keydown) until mouse is clicked

推荐答案

为什么使用(keyup/keydown)直到单击鼠标时才触发更改事件

why change event not fired when using (keyup/keydown) until mouse is clicked

当焦点离开select时也会闪光.这就是change事件的工作方式.

It also fires when focus leaves the select. That's just how the change event works.

如果要主动通知,则必须注意changekeydown(至少也可能需要click),并在值未实际更改的情况下处理获取事件的情况. ,,您必须处理以下事实:在值更改前 ,其中的某些事件(例如keydown)被触发了,因此您必须稍等片刻在处理事件之前.或参见 SpYk3HH的答案,该答案使用keyup代替.这样会减少主动性(可能不希望在密钥发布之前才进行更新),但是您不需要我的以下代码具有延迟(setTimeout).

If you want proactive notification, you have to watch for change and keydown (at least, you may want click as well) and handle the case of getting an event when the value hasn't actually changed, and you have to handle the fact that some of those events (keydown, for instance) are fired before the value is changed, so you have to wait a moment before processing the event. Or see SpYk3HH's answer which uses keyup instead — that will be less proactive (not updating until key release, which could be desireable), but then you don't need the delay (setTimeout) my code below has.

示例(活动副本):

HTML(我可以自由地更改值,因此每个名称都带有更清晰的名称):

HTML (I took the liberty of changing the values so it was clearer which went with each name):

<select id="users">
<option value="j">jack</option>
<option value="b">brill</option>
<option value="a">antony</option>
</select>​

JavaScript:

JavaScript:

$("#users").bind("keydown change", function(){
    var box = $(this);
    setTimeout(function() {
        display(box.val());
    }, 0);
});


2016年的注意事项:bind在很大程度上已由 on 取代.在上面,您实际上只是将"bind"替换为"on".


Note in 2016: bind has largely been replaced with on. In the above it you'd literally just replace "bind" with "on".

这篇关于&lt;选择&gt;使用键盘时未触发更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆