Javascript OnKeyPress ENTER 重新加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12781308/
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
OnKeyPress ENTER Reloads The Page
提问by shadyinside
<input type="text" onkeypress="if (event.keyCode==13){ func_name(this.value);}" id="userinput"/>
I have a textfield where i have called a function on hitting the ENTER key.The problem is that the page gets reloaded while it should not have been so as i am calling only a js function.Please tell me what am i doing wrong.
我有一个文本字段,我在其中按 ENTER 键调用了一个函数。问题是页面被重新加载,而它不应该被重新加载,因为我只调用了一个 js 函数。请告诉我我做错了什么。
回答by Billy Moon
The form is being submitted by the pressing of enter. You can attach an onsubmit
event to the form, and return false to prevent submission (and true to submit). YOu can use this feature to validate the data before submitting, or to intercept your keypress
event.
按回车键正在提交表单。您可以将onsubmit
事件附加到表单,并返回 false 以阻止提交(并返回 true 以提交)。您可以使用此功能在提交前验证数据,或拦截您的keypress
活动。
Alternatively, as commented on below, you can use event.preventDefault() to prevent the pressing of enter triggering a submit.
或者,正如下面所评论的,您可以使用 event.preventDefault() 来防止按下 Enter 触发提交。
Something like this...
像这样的东西...
<form action=".">
<input type="text" onkeypress="console.log('happy days'); event.preventDefault()">
</form>
回答by Mauro Maximiliano Martinez
I know this is an old message, but I solved it adding "return false":
我知道这是一条旧消息,但我解决了它并添加了“return false”:
<input type="text" onkeypress="if (event.keyCode==13){ func_name(this.value);return false;}" id="userinput"/>
Maybe it is usefull to other with a similar issue.
也许它对其他有类似问题的人有用。