3

我试图在有人输入一些信息后发送信息,如果有人通过单击其他地方或跳出离开,它会发送信息....但是当按下回车键时,它会中断并转到下一行。我试图阻止这种情况,并在他们按 Enter 时离开该框。

代码:

$('.username').blur(function(){
    if (username != $(this).text()) {
        $.ajax({
            type: 'POST',
            url: 'usernameChange',
            data: { username: username, id: id }
        }).done(function(msg){
            console.log('Okay, new username is ' + msg);
        });
    }
});

如何检查是否有人按Enter键离开...

<span class="username" contenteditable="true">Nasus</span>
4

1 回答 1

3

您必须处理 keydown 事件,以便在有人按下 Enter 键时失去对 contentEditable 的关注,这样您还可以防止换行。

$(".username").on("keydown",function(e){
    var key = e.keyCode || e.charCode;  // ie||others
    if(key == 13)  // if enter key is pressed
        $(this).blur();  // lose focus
});
于 2013-11-09T16:31:14.983 回答