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条回答
闹够了就滚
2楼-- · 2020-03-11 18:17

could it be possible that your html-element is contained twice within txt?

it would be helpful if you would provide the html and the assigning javascript-code.

查看更多
劳资没心,怎么记你
3楼-- · 2020-03-11 18:18

I know it's been quite awhile, but I'm surprised nobody suggested:

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

If somehow txt got bound already, calling unbind before your new bind should fix it. Of course it's preferable to figure out why it's being bound twice. This just happened to me, because I accidentally had my JavaScirpt file included twice. Calling unbind helped me determine that was the problem.

查看更多
登录 后发表回答