javascript防止keyup的默认值

Rya*_*ing 11 javascript jquery

我有以下代码:

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true"></p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        alert("Should remove element.");
        $(this).remove();
        $(this).previous('p').focus();
    };
});
Run Code Online (Sandbox Code Playgroud)

我想在按下某个键时阻止默认操作.preventDefault适用keypress但不适用keyup.有没有办法防止违法行为$(document).on('keyup')

Nor*_*ard 32

keyup的默认操作之后激发.

keydown并且keypress是您可以阻止默认的地方.
如果没有停止,则默认发生并被keyup触发.


Siv*_*ini 7

我们可以使用以下代码片段来阻止该操作。

e.stopPropagation();
      e.preventDefault();  
      e.returnValue = false;
      e.cancelBubble = true;
      return false;
Run Code Online (Sandbox Code Playgroud)

keyup 在 keydown/keypress 之后触发。我们可以防止任何这些事件中的默认操作。

谢谢,

湿婆

  • 这不是所提问题的正确答案,否则我会投票;不过,我真的很感谢您为提供这些有用信息所做的努力。 (3认同)