jQuery: textbox keyup firing twice

2020-03-11 17:34发布

I'm having a textbox and assigned the following function (it's the only function assigned):

txt.bind("keyup",function(event){
    if(event.keyCode==13)
    {
        var nu = $("#debug").html();
        nu+="<br>enter";
        $("#debug").html(nu);
    }
});

The strange thing is that it's actually firing twice, thus displaying "enter" twice in my debug window. Does anyone know what is causing this?

标签: jquery bind
8条回答
Deceive 欺骗
2楼-- · 2020-03-11 18:00

Here's my workaround for the same issue:

$('input').live('keyup keydown', function(e) {
    var thisKey = e.keyCode ? e.keyCode : e.which;
    if (thisKey == 13) {
        e.preventDefault();
        e.stopPropagation();
        if (e.type == 'keyup') {
            $(this).closest('form').submit();   
        }
    }
});
查看更多
够拽才男人
3楼-- · 2020-03-11 18:01

I'm embarrassed to even mention this, but I was typing a capital letter into my textbox and so the release of my shift key was causing the supposed "second firing" of the keyup event. Turns out it wasn't a second firing at all, but it just fooled me into thinking it was for while. At first I thought the unbind trick mentioned above simply wasn't working for me, but it was. I hope this helps others like me that might have done the same thing. Now I simply make sure I always check that its not just the shift key being released in the handling of my event and all is well again.

查看更多
可以哭但决不认输i
4楼-- · 2020-03-11 18:08

I had the same problem. Though i could not find a solution yet, i found the reason why it is triggering twice.

I am handing the event if the entered text has "@".For this i am listing each key stroke. To enter '@' you need two key precesses (@+shift) and that is the reason it is triggering twice.

查看更多
smile是对你的礼貌
5楼-- · 2020-03-11 18:10

I had a similar problem
found that object with assigned keyup function was inside another object
first was div second was input
found that keyup was assigned to input and to a div with this input

查看更多
Anthone
6楼-- · 2020-03-11 18:13

I'm having the same issue - keyup and keydown events are being fired twice though their handlers are bound only once and I'm definitely attaching them to only one element.

The interesting point is that this behavior can be observed only in Internet Explorer and in just one special case where my webapp is displayed in an embedded ActiveX control (CLSID_InternetExplorer). OS: Windows 7, IE 8, embedded ActiveX control is running in IE7 compatibility mode.

I've found a workaround however - process the jQuery's keypress event, which made also more semantic sense in my webapp.

查看更多
爷的心禁止访问
7楼-- · 2020-03-11 18:15

i found out by myself - txt.bind was assigned twice to the textbox so it fired twice. is this a bug? i thought binding a function will always fire just once .. hmm

查看更多
登录 后发表回答