jQuery:防止输入键
我试图阻止将 enter 键放入文本区域,但它似乎不起作用。
$('#comment').keyup(function(event) {
if (event.text.charCodeAt() == '10') {
event.preventDefault();
}
});
I am trying to prevent the enter key from being put into a textarea, but it doesn't seem to work.
$('#comment').keyup(function(event) {
if (event.text.charCodeAt() == '10') {
event.preventDefault();
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我在 jsfiddle.net 上写了一些演示,您可以在其中尝试此代码
每个人都有正确的答案:)
I have written little demonstration on jsfiddle.net, where you can try this code
Everybody has right answer :)
您无法取消
keyup
事件。不过,您可以取消keydown
和keypress
事件。在文档中,请注意在“事件信息”下,keyup
的“取消”为“否”:使用
keydown
可以让您取消比keypress
更多的按键,但如果您不想在按键被抬起之前取消,keypress< /code> 就是你想要的。幸运的是,回车键是
keypress
事件的可取消键之一。You can't cancel a
keyup
event. You can cancelkeydown
andkeypress
events though. In the documentation, notice that under "Event Information", "Cancels" is "No" forkeyup
:Using
keydown
allows you to cancel far more keys thankeypress
, but if you don't want to cancel until after the key has been lifted,keypress
is what you want. Fortunately for you, the enter key is one of the cancellable keys for thekeypress
event.在
keydown
事件中使用event.keyCode
:Use
event.keyCode
in thekeydown
event:虽然此处提供的答案将阻止某人输入回车符,但不会阻止某人粘贴回车符。
您需要对文本进行一些后期处理(在 JavaScript 或服务器端)以删除它们。
http://jsfiddle.net/we8Gm/
但问题是,为什么?为什么不简单地使用
它会自动处理这个问题,因为它是单行输入元素?
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.
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?尝试使用
.keypress
并使用return false
;祝你好运!
Try with
.keypress
and usereturn false
;Good luck!