将焦点集中到更改回调中的另一个控件时,jQuery更改事件触发两次 [英] jQuery change event fired twice when giving focus to another control inside the change callback

查看:69
本文介绍了将焦点集中到更改回调中的另一个控件时,jQuery更改事件触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个奇怪的错误最近让我感到很头疼,而且我已经能够将它简化为最简单的形式。看到这个小提琴: http://jsfiddle.net/PgAAb/

 < input type =textid =fooplaceholder =改变我!>< br> 
< input type =textid =barsize =30placeholder =虚拟控制切换焦点>
$ b $('#foo')。change(function(){
console.log('Changed!');
$('#bar')。focus );
});

基本上,当您更改第一个文本框并使用鼠标单击文档中的其他位置时,事件像往常一样火灾。但是,如果您更改了该值,然后按Enter键以触发更改,则该事件将触发两次。



我注意到该错误仅适用于Chrome。 Firefox不会触发事件两次,IE甚至不支持输入键来触发输入变化。



我猜这是因为焦点切换事件回调。有没有办法解决这个问题?

解决方案

你的change eventhandler中的其他控件的focus()调用chrome中的change事件,因为如果值不同,它将忽略模糊你当前的控件。



这个bug并不新鲜,你可以在jQuery上看看这个bug票: http://bugs.jquery.com/ticket/9335



您可以通过禁用更改事件处理程序来解决此问题,以删除控件上的焦点。
这里有一点我想说的例子:

$ $ $('#foo')。change(changeHandler );

function changeHandler(){
console.log('Changed!'); ('change',changeHandler);
$(this).off('change')。blur()。
$('#bar')。focus();
}


A weird bug caused me a lot of headaches recently, and I've been able to dumb it down to the simplest form possible. See this fiddle : http://jsfiddle.net/PgAAb/

<input type="text" id="foo" placeholder="Change me!"><br>
<input type="text" id="bar" size="30" placeholder="Dummy control to switch focus">

$('#foo').change(function() {
    console.log('Changed!');
    $('#bar').focus();
});

Basically, when you change the first textbox and use the mouse to click elsewhere in the document, the change event fires, as usual. However, if you change the value, and hit the enter key to trigger the change, the event fires twice.

I've noticed the bug is only with Chrome. Firefox does not trigger the event twice, and IE does not even support the enter key to trigger change on an input.

I guess that happens because of the focus switching inside the event callback. Is there any way around this?

解决方案

The focus() on other control in your change eventhandler call the change event in chrome because it unfocus "blur" your current control if the value is different.

This bug is not new, you can take a look at this bug ticket on jQuery : http://bugs.jquery.com/ticket/9335

You can work around this by disabling the change eventhandler before to remove the focus on your control. Here a little exemple of what I want to say:

$('#foo').change(changeHandler);

function changeHandler() {
    console.log('Changed!');
    $(this).off('change').blur().on('change', changeHandler);
    $('#bar').focus();
}

这篇关于将焦点集中到更改回调中的另一个控件时,jQuery更改事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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