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)" />
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.
(为了在按下Enter键时从此文本框中运行某些“用户定义”脚本,而不让其提交表单,下面是一些示例代码。)
Please note that this function doesn't do any error checking and most likely will only work in IE. (请注意,此功能不执行任何错误检查,很可能仅在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.
(返回该函数的值将警告事件处理程序不要再使事件冒泡,并且将防止进一步处理keypress事件。)
NOTE: (注意:)
It's been pointed out that keyCode
is now deprecated .
(已经指出, keyCode
现在已弃用 。)
The next best alternative which
has also been deprecated . (接下来的最佳替代品which
已也被弃用 。)
Unfortunately the favored standard key
, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge .
(不幸的是,受现代浏览器广泛支持的受青睐的标准key
在IE和Edge中具有某些躲避行为 。)
Anything older than IE11 would still need a polyfill . (IE11之前的任何版本都仍需要polyfill 。)
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.
(此外,尽管已过时的警告对于keyCode
和which
是非常不祥的,但删除这些警告将代表着无数旧版网站的巨大突破。)
For that reason, it is unlikely they are going anywhere anytime soon. (因此, 他们不太可能很快就去任何地方。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…