jQuery javascript防止keyup的默认设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16052592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:16:55  来源:igfitidea点击:

javascript prevent default for keyup

javascriptjquery

提问by Ryan King

I have the following code:

我有以下代码:

$(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();
    };
});

I would like to prevent the default action when a key is pressed. preventDefaultworks for keypressbut not keyup. Is there a way to prevent the defualt for $(document).on('keyup')?

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

回答by Norguard

No. keyupfires after the default action.

No.keyup在默认操作后触发。

keydownand keypressare where you can prevent the default.
If those aren't stopped, then the default happens and keyupis fired.

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

回答by SivaRajini

We can prevent the action by using following code snippet.

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

e.stopPropagation();
      e.preventDefault();  
      e.returnValue = false;
      e.cancelBubble = true;
      return false;

keyup fires after keydown/keypress. we can prevent default action in anyone of those events.

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

Thanks,

谢谢,

Siva

湿婆