简体   繁体   English

当我在选择中使用向上或向下箭头时,为什么jquery不会更改事件?

[英]why doesn't the jquery change event fire when i use the up or down arrows on a select?

I am listening to the change event of a select dropdown using jquery and the livequery plugin. 我正在使用jquery和livequery插件监听选择下拉列表的更改事件。

$(".myDropdown").livequery("change", function () {
});

one thing i noticed (i am using firefox) is that 我注意到的一件事(我使用的是firefox)就是这样

The event handler doesn't fire from hitting the up and down arrows when i have the select focused (the up and down arrow DO change the entries) 当我选择聚焦时,事件处理程序不会触发向上和向下箭头(向上和向下箭头DO更改条目)

Why doesn't the change event fire when i move the arrows key up and down and is there a recommendation or workaround for this? 当我上下移动箭头键时,为什么更改事件不会触发?是否有推荐或解决方法?

If what Malvolio says is true, then that should work 如果Malvolio说的是真的那么,那应该有用

$(".myDropdown").livequery("change", function () {
   // your event handler
}).livequery("keypress", function() { 
   $(this).trigger("change");
});

http://jsfiddle.net/tW6Su/2/ as proof http://jsfiddle.net/tW6Su/2/作为证明

I suppose I'll summarize. 我想我会总结一下。

If you click an item in the select box you are changing it. 如果单击选择框中的项目,则表示您正在更改它。 If you go downward through the select box by keying through it is not selected until you press enter, click off or tab away. 如果您通过键入向下浏览选择框,则只有按Enter键才能选中,单击关闭或标签。 I suppose this differs slightly from browser to browser, but essentially the selection occurs on something like a "i'm completely done with this form field and moved away now" event. 我认为这在浏览器与浏览器之间略有不同,但实际上选择发生在类似“我已完全使用此表单字段并立即离开”事件。

If you would like the result to be more immediate you could either trigger the change event like this: 如果您希望结果更直接,您可以触发更改事件,如下所示:

$("select").live("keypress",function(){
    $(this).trigger("change");
});

If you would like that to occur on all form fields try this selector: $(":input select textarea") 如果您希望在所有表单字段上执行此操作,请尝试以下选择器: $(":input select textarea")

This following code (on Firefox 3.6 anyway) agrees with the OP and disagrees with the commenters: 以下代码(无论如何在Firefox 3.6上)同意OP并且不同意评论者:

$('body').append('<select/>').find('select')
    .append('<option>one</option)')
    .append('<option>two</option>')
$('body').find('select').keypress(function() { 
    console.log('keypress: ' + $(this).val()); })

Whenever you hit an arrow key, a changed value is printed to the log. 只要按箭头键,就会在日志中打印更改的值。

Change events are not on fired until the element loses focus, even though you are changing the value (as Malvolio proved). 在元素失去焦点之前,更改事件不会被触发,即使您正在更改值(正如Malvolio所证明的那样)。 The following code snippet will manually fire the change event when any key is pressed: 以下代码片段将在按下任何键时手动触发更改事件:

$("select").on("keypress",function(){
    $(this).trigger("change");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM