Javascript 尝试将输入单击绑定到字段的 onkeyup 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14087753/
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
trying to bind enter click to onkeyup event of a field
提问by Neta Meta
So in normal situation where jquery i allowed and i can bind the field onkeyup i would use:
所以在 jquery 我允许的正常情况下,我可以绑定字段 onkeyup 我会使用:
$('#something').keyup(function(e) {
var enterKey = 13;
if (e.which == enterKey){
somefunction();
}
});
however i cannot use this and will have to use something like:
但是我不能使用它,必须使用类似的东西:
<input id="something" onkeyup="onkeyup_colfield_check(this)" type="text">
function onkeyup_colfield_check(e){
var enterKey = 13;
if (e.which == enterKey){
somefunction();
}
}
However this doesn't work like the above.
然而,这不像上面那样工作。
how can i achieve the same result like the first example but with something like that?
我怎样才能获得与第一个示例相同的结果,但使用类似的方法?
回答by jeremy
You need to pass in eventas an argument, not this.
您需要event作为参数传入,而不是this.
<input id="something" onkeyup="onkeyup_colfield_check(event)" type="text">
Also, to be fully compatible with all major browsers, you may want to use the following for detecting te key code of the key pressed.
此外,为了与所有主要浏览器完全兼容,您可能需要使用以下内容来检测按下的键的键代码。
var charCode = (typeof e.which === "number") ? e.which : e.keyCode;

