javascript Select Element onChange 事件没有触发?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6551243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select Element onChange event is not firing?
提问by RyanScottLewis
I have a select element with an onChange event that doesfire when I click the select box and select a new value within it. But, when I tab to the select box and press the up or down arrows to change the select box's value, the event does not fire.
我有一个带有 onChange 事件的 select 元素,当我单击选择框并在其中选择一个新值时会触发该事件。但是,当我跳到选择框并按向上或向下箭头更改选择框的值时,该事件不会触发。
I am using jQuery().change(function(){ ... });
to set the event
我正在使用jQuery().change(function(){ ... });
设置事件
采纳答案by FishBasketGordo
When you tab into a <select>
element, the change event doesn't fire until you press the Enter key.
当您按 Tab 键进入<select>
元素时,更改事件在您按下 Enter 键之前不会触发。
回答by David says reinstate Monica
For an onChange()
to fire the value must be changed andthe input
must be blur()
-ed (focus moved elsewhere); which is why it fires in your first case, but not in the second.
对于onChange()
火的值必须改变和在input
必须blur()
-ed(焦点移到别处); 这就是为什么它会在您的第一种情况下触发,但不会在第二种情况下触发。
The change event is sent to an element when its value changes. This event is limited to
<input>
elements,<textarea>
boxes and<select>
elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
当元素的值发生变化时,将更改事件发送到元素。此事件仅限于
<input>
元素、<textarea>
框和<select>
元素。对于选择框、复选框和单选按钮,当用户使用鼠标进行选择时会立即触发该事件,但对于其他元素类型,该事件会推迟到该元素失去焦点时。
Reference:
参考:
回答by Robert
As others have stated, the change event doesn't happen until the blur event. You'll need to monitor keyup as well to capture someone moving changing the values with the arrow keys.
正如其他人所说,更改事件直到模糊事件才会发生。您还需要监视 keyup 以捕获有人移动使用箭头键更改值。
Monitor keyup and change,
监控按键和变化,
$('select').bind('change keyup', function() {
// Handle
});
回答by Niklas
You can trigger the blur
event on keyup
on the select
and then give back focus
, which will trigger the change:
您可以blur
在keyup
上触发事件select
,然后返回focus
,这将触发更改:
$('select').keyup(function(){
$(this).blur().focus();
});
example: http://jsfiddle.net/niklasvh/XEg36/