Javascript jQuery:防止输入键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4753823/
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-23 13:55:19  来源:igfitidea点击:

jQuery: Prevent enter key

javascriptjqueryhtmlkeypressforms

提问by James T

I am trying to prevent the enterkey from being put into a textarea, but it doesn't seem to work.

我试图阻止将enter密钥放入 textarea,但它似乎不起作用。

$('#comment').keyup(function(event) {
  if (event.text.charCodeAt() == '10') {
     event.preventDefault();
   }
});

回答by kajo

I have written little demonstration on jsfiddle.net, where you can try this code

我在jsfiddle.net上写了一些演示,你可以在那里试试这个代码

Everybody has right answer :)

每个人都有正确的答案:)

$('#comment').keypress(function (event) {
    if (event.keyCode === 10 || event.keyCode === 13) {
        event.preventDefault();
    }
});

回答by gilly3

You can't cancel a keyupevent. You can cancel keydownand keypressevents though. In the documentation, notice that under "Event Information", "Cancels" is "No" for keyup:

您无法取消keyup活动。你可以取消keydownkeypress事件。在文档中,请注意在“事件信息”下,“取消”为“否” keyup

Using keydownallows you to cancel far more keys than keypress, but if you don't want to cancel until after the key has been lifted, keypressis what you want. Fortunately for you, the enter key is one of the cancellable keys for the keypressevent.

Usingkeydown允许您取消比 多得多的键keypress,但如果您不想在取消键后取消,keypress这就是您想要的。幸运的是,回车键是keypress事件的可取消键之一。

回答by Jacob Relkin

Use event.keyCodein the keydownevent:

使用event.keyCodekeydown事件:

$('#comment').keydown(function(event) {
   if(event.keyCode == 13) return false;
   //carry on...
});

回答by ThiefMaster

$('#comment').keypress(function(event) {
    if (event.keyCode == 13) {
        event.preventDefault();
    }
});

回答by Gonzalo Larralde

Try with .keypressand use return false;

尝试.keypress并使用return false

Good luck!

祝你好运!

回答by Jeff B

While the answers provided here will prevent someone from typing a carriage return, it will not prevent someone from pasting one in.

虽然此处提供的答案会阻止某人输入回车符,但不会阻止某人粘贴回车符。

You would need to do some post processing of the text (in javascript or server-side) to remove them.

您需要对文本进行一些后期处理(在 javascript 或服务器端)以删除它们。

http://jsfiddle.net/we8Gm/

http://jsfiddle.net/we8Gm/

But the question is, why?Why not simply use <input type="text"></input>which takes care of this automatically as it is a single-line input element?

但问题是,为什么?为什么不简单地使用<input type="text"></input>which 自动处理这个问题,因为它是一个单行输入元素?