javascript 按下回车键时不刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25615758/
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
Don't refresh page when enter key is pressed
提问by cardboardtheory
I'm having some problems with the enter key triggering a refresh of the page whenever there is input in a form.
每当表单中有输入时,回车键都会触发页面刷新,我遇到了一些问题。
The following code does not refresh the page if enter is pressed and if there is no text inputted in the text area (#input) but will refresh the page if enter is pressed and there is input in #input OR if the cursor is in the text area. I'm not sure what's triggering it, as #submit is a regular button.
如果按下 Enter 并且文本区域 (#input) 中没有输入文本,以下代码不会刷新页面,但如果按下 Enter 并且 #input 中有输入或光标位于文本区域。我不确定是什么触发了它,因为#submit 是一个普通按钮。
<div id="forms" class="container">
<form>
Enter your verb here in plain (dictionary) form:
<input type="text" class="input-sm" id="input"></input>
<div class="radio">
<label>
<input type="radio" name="input-method" value="Hiragana" checked />Radio 1
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="input-method" value="Romaji" />Radio 2
</label>
</div>
<input type="button" class="btn btn-default" id="submit" value="Submit">
</input
</form>
</div>
I'm trying to jquery to solve the problem, but need help in that regard. Any suggestions would be appreciated!
我正在尝试使用 jquery 来解决问题,但在这方面需要帮助。任何建议,将不胜感激!
回答by Amol
you can either add following script at the end of body
您可以在正文末尾添加以下脚本
<script>
$("form").submit(function (e) {
e.preventDefault();
alert("call some function here");
});
</script>
or you can just put your form tag like this
或者你可以像这样放置你的表单标签
<form onsubmit="return false">
either way you will then have to write an onClick="SOMEFUNCTION()" to the input
无论哪种方式,您都必须将 onClick="SOMEFUNCTION()" 写入输入
also there is an error with an extra /button tag...remove that and instead use
额外的 /button 标签也有错误......删除它并使用
<input type="button" class="btn btn-default" id="submit" value="Conjugate" />
note the ending slash
注意结尾斜线
回答by Axel Amthor
回答by Super Hornet
you have syntax error in your html codes:
您的 html 代码中有语法错误:
<input type="button" class="btn btn-default" id="submit" value="Submit">
</button>
change it to this:
把它改成这样:
<button type="button" class="btn btn-default" id="submit" value="Submit">
</button>
Also, you need using Javascript/jquery to submit your form to prevent refreshing your entire page
此外,您需要使用 Javascript/jquery 提交表单以防止刷新整个页面
回答by Rhys
place :
e.preventDefault();
inside the keypress function
地方:
e.preventDefault();
按键功能内