问题描述
我有一个表单
,其中有两个文本框,一个 select 下拉菜单和一个单选按钮。当按下键时,我想调用我的JavaScript函数,但是当我按下它时,会提交表单
。
I have a form
with two text boxes, one select drop down and one radio button. When the key is pressed, I want to call my JavaScript function, but when I press it, the form
is submitted.
如何在按下键时阻止提交表单
?
推荐答案
if(characterCode == 13)
{
return false; // returning false will prevent the event from bubbling up.
}
else
{
return true;
}
好,因此,假设您有以下文本框:
Ok, so imagine you have the following textbox in a form:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
要在按下Enter键时从此文本框中运行一些用户定义脚本,并没有提交表单,这是一些 sample 代码。请注意,此功能不执行任何错误检查,很可能仅在IE中有效。要做到这一点,您需要一个更强大的解决方案,但您将获得一般的想法。
In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.
function runScript(e) {
//See notes about 'which' and 'key'
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
返回该函数的值将提醒事件处理程序
returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.
已指出, keyCode
是。下一个最佳选择,其中
具有。
It's been pointed out that keyCode
is now deprecated. The next best alternative which
has also been deprecated.
不幸的是,受到青睐的标准 key
在现代浏览器中,它在IE和Edge中具有。早于IE11的任何版本仍需要。
Unfortunately the favored standard key
, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.
此外,虽然已弃用的警告对于 keyCode
和哪个
来说是不祥的,但删除那些代表对无数旧网站的巨大突破。因此,他们不太可能很快就去任何地方。
Furthermore, while the deprecated warning is quite ominous about keyCode
and which
, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.
这篇关于防止在Enter键上提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!