Javascript HTML 表单 - 当我按下回车键时,它会刷新页面!
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2215462/
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
HTML form - when I hit enter it refreshes page!
提问by Sharon
Is there a way to make a form NOT refresh or call anything when you hit "Enter" key on your keyboard?
当您按键盘上的“Enter”键时,有没有办法使表单不刷新或调用任何内容?
Thank you so much!!!
非常感谢!!!
I found this code for preventing Enter from working, but it DOESN'T work in IE :(
我发现这段代码可以防止 Enter 工作,但它在 IE 中不起作用 :(
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
}
回答by icktoofay
Try this:
尝试这个:
$(function() {
$("form").submit(function() { return false; });
});
回答by BalusC
Disabling the submitevent isn't a good idea. Now you can neversubmit the form by pressing the button where it is for.
禁用该submit事件不是一个好主意。现在,您永远无法通过按其所在的按钮来提交表单。
Rather hook on the keypressevent:
而是钩在keypress事件上:
<form onkeypress="return event.keyCode != 13">
or in jQuery flavor:
或 jQuery 风格:
$('form').keypress(function(event) {
return event.keyCode != 13;
});
13is the keyCode of Enterkey. This works in all browsers from IE6 up to with all the current ones. You only have to take textareas into account. You may then consider this construct instead:
13是Enterkey的keyCode 。这适用于从 IE6 到所有当前浏览器的所有浏览器。您只需要考虑文本区域。然后,您可以考虑使用此构造:
$(':input:not(textarea)').keypress(function(event) {
return event.keyCode != 13;
});
回答by PatlaDJ
add onSubmit property on form's tag.
在表单标签上添加 onSubmit 属性。
<form onSubmit="return false;">
回答by Maxim Demkin
You can prevent form submission by 'enter' key natively if you are using AngularJS.
如果您使用的是 AngularJS ,则可以通过本机的“输入”键阻止表单提交。
According to HTML specification and AngularJS, you need to check this list:
根据 HTML 规范和 AngularJS,你需要检查这个列表:
- Form must have NO
action=...attribute (AngularJS handles it automatically) - Form must have NO
buttonwithtype="submit"attribute
- 表单必须没有
action=...属性(AngularJS 会自动处理它) - 表格必须有否
button与type="submit"属性
So, if you have no action attribute and submit button, then your form should not be submitted by hitting enter key.
因此,如果您没有 action 属性和提交按钮,则不应通过按 Enter 键提交表单。
Also, cross-browser keyCode is this:
此外,跨浏览器的 keyCode 是这样的:
var code = (e.keyCode ? e.keyCode : e.which);

