javascript 在文本框中按 Enter 后防止模糊和键盘事件触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11143011/
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
Prevent both blur and keyup events to fire after pressing enter in a textbox
提问by Bhavesh Gangani
After pressing enterI would like that only the keyup
event be fired but blur
is fired first. How to cancel blur
when keyup
is fired with enter?
按下后,enter我希望只有keyup
事件被触发,但blur
首先被触发。被解雇blur
时如何取消?keyup
enter
Please don't suggest to bind both blur
and keyup
into a single live()
method.
请不要建议结合两者blur
并keyup
成一个单一的live()
方法。
$(".textbox").on("blur",function () {
alert("blur Event fired");
});
$(".textbox").on("keyup",function (event) {
if(event.keyCode == 13){ // Detect Enter
alert("KeyUp fired after pressing Enter");
}
});
采纳答案by Bhavesh Gangani
I Couldn't alter class
attribute so i'd ended up with,
我无法改变class
属性所以我结束了,
$(".textbox").on("blur",function () {
if($(this).attr('flag')!='1')
alert("blur Event fired");
});
$(".textbox").on("keyup",function (event) {
$(this).attr('flag','1');
if(event.keyCode == 13){ // Detect Enter
alert("KeyUp fired after pressing Enter");
}
$(this).attr('flag','0');
});
回答by Chris Baker
Edit
编辑
To prevent both events from firing, you'll have to somehow mark the element before causing it to lose focus. That way, your blur
event handler can tell if the event is the subject of a keyup, or if it legitimately lost focus. Something like this:
为了防止触发这两个事件,您必须在导致元素失去焦点之前以某种方式标记该元素。这样,您的blur
事件处理程序可以判断该事件是否是按键的主题,或者它是否合法地失去了焦点。像这样的东西:
$(".textbox").live("blur",function (event) {
if (!$(this).hasClass('keyupping'))
alert("blur Event fired");
});
$(".textbox").live("keyup",function (event) {
$(this).addClass('keyupping');
if(event.keyCode == 13){ // Detect Enter
alert("KeyUp fired after pressing Enter");
}
$(this).removeClass('keyupping');
});
Try it out: http://jsfiddle.net/GRMule/sR6zm/
试试看:http: //jsfiddle.net/GRMule/sR6zm/
Original answer
原答案
When the event for keyup
fires, it prepares to draw the browser alert dialog, which takes focus from the document and applies it to the modal dialog. This causes the blur event to fire.
当事件 forkeyup
触发时,它准备绘制浏览器警报对话框,该对话框从文档中获取焦点并将其应用于模式对话框。这会导致模糊事件触发。
The blur
event is then jumping in and finishing its execution context before keyup
knows what hit it.
然后blur
事件在keyup
知道是什么击中它之前跳入并完成其执行上下文。
This is demonstrated by using something that does nottake the focus off the element, like console.log
: http://jsfiddle.net/GRMule/7vRLW/
这是通过使用不会将焦点从元素上移开的东西来证明的,例如console.log
:http: //jsfiddle.net/GRMule/7vRLW/
The order that events fire is implementation-specific, meaning that you can't rely on Firefox acting like IE. See the spec: http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-eventgroupings. Try the fiddle with alerts in IE, and in this case you'll see that blur
does hit before keyup
in IE 7 -- and blur
doesn't fire in Chrome!
事件触发的顺序是特定于实现的,这意味着您不能像 IE 一样依赖 Firefox。请参阅规范:http: //www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-eventgroupings。尝试在 IE 中处理警报,在这种情况下,您会看到它blur
之前keyup
在 IE 7blur
中触发过——并且在 Chrome 中没有触发!
回答by xtempore
I had a similar problem. I'm allowing the user to edit a single field and when they press Enter or move off that field, I send an Ajax request to update it. I found that when I pressed Enter the Ajax request was sent twice.
我有一个类似的问题。我允许用户编辑单个字段,当他们按 Enter 键或移出该字段时,我会发送一个 Ajax 请求来更新它。我发现当我按下 Enter 时,Ajax 请求被发送了两次。
So rather than calling my request on Enter, I tried calling $input.blur()
instead, and that worked! Which got me to thinking... If the Enter key causes a blur do I even need to try to capture it?
因此,我没有在 Enter 上调用我的请求,而是尝试调用$input.blur()
,结果奏效了!这让我开始思考......如果 Enter 键导致模糊,我什至需要尝试捕捉它吗?
In my case, I did not need to. I found that all I needed was the blur because the Enter key triggered it anyway. I'm not sure if that's 100% across all browsers, but I did test on current versions of Chrome, Firefox, IE and Safari, all of which worked fine.
就我而言,我不需要。我发现我需要的只是模糊,因为 Enter 键无论如何都会触发它。我不确定这是否在所有浏览器中都是 100%,但我确实在当前版本的 Chrome、Firefox、IE 和 Safari 上进行了测试,所有这些都运行良好。
So, I suggest that you either just don't capture the Enter at all, or you simply call blur() to trigger the actions you need.
因此,我建议您要么根本不捕获 Enter,要么只需调用 blur() 来触发您需要的操作。
回答by Emre
I have an input where a user can change it, focus out or press enter.
But when you press enter both keydown and blur is triggered, so myFunction()
gets triggered twice.
我有一个输入,用户可以在其中更改它、聚焦或按 Enter。但是当你按下回车键和模糊被触发,所以myFunction()
被触发两次。
So instead of writing two separate functions for keydown
and blur
, you can instead put them into a single function:
因此,与其为keydown
and编写两个单独的函数blur
,不如将它们放入一个函数中:
my_input.on('keydown blur', function (e) {
// was it the Enter key?
if (e.which == 13) {
$(this).blur();
}
if (e.type == 'blur') {
myFunction();
}
});
回答by Teela
The below code worked for me, in primefaces 5.2.5
下面的代码对我有用,在primefaces 5.2.5
<p:inputText onkeydown="if (event.keyCode === 13) {return false; }" value="#{myForm.name}">
<p:ajax event="blur" update="@this" listener="#{bean.func()}" />
</p:inputText>
<p:inputText onkeydown="if (event.keyCode === 13) {return false; }" value="#{myForm.name}">
<p:ajax event="blur" update="@this" listener="#{bean.func()}" />
</p:inputText>
Blur event was not triggered even though Enter key was pressed.
即使按下 Enter 键,也未触发模糊事件。
回答by Raoni Souza Cunha
Basically, keyup
is a trigger for blur
event. You should add a flag when keyup fires:
基本上,keyup
是blur
事件的触发器。您应该在 keyup 触发时添加一个标志:
$('#exemple').keyup(function (e) {
if (e.which == 13) {
$('#exemple').addClass('keyupfired');
alert('whatever');
}
});
Then, when blur
is fired, it should ask if keyup
has already been fired too. Remember to remove the flag if you want the event to be fired when the user get off the textbox:
然后,当blur
被触发时,它应该询问是否keyup
也被触发了。如果您希望在用户离开文本框时触发事件,请记住移除标志:
$('#exemple').on("blur", function () {
if (!$('#exemple').hasClass('keyupfired')) {
alert('whatever');
}
$('#exemple').removeClass('keyupfired');
});
回答by Austin Wang
Try the following. Adding a class -- addedin this example, in the keyup event handler and modifying the selector for the blur event will prevent the blur event handler from firing.
请尝试以下操作。添加一个类——在本例中添加到 keyup 事件处理程序中并修改模糊事件的选择器将阻止模糊事件处理程序触发。
$(".textbox:not(.added)").on("blur", function () {
alert("blur Event fired");
});
$(".textbox").on("keyup", function (event) {
if (event.keyCode == 13) {
$(event.currentTarget).addClass('added');
alert("KeyUp fired after pressing Enter");
}
});
回答by bstenm
It has been brought to my attention than rather then providing hints I should give more complete explanations and code examples, so here it is: there is always the cheap way of setting a external variable:
它引起了我的注意,而不是提供提示,我应该给出更完整的解释和代码示例,所以这里是:总是有设置外部变量的廉价方法:
var triggerBlur = true;
$(".textbox")
.live({
blur : function () {
if (triggerBlur) {// if not preceded by keyup 'Enter' event
alert("blur Event fired");
}
// reset variable to true to allow the blur event to be triggered subsequently when not preceded by keyup 'Enter' event
triggerBlur = true;
},
keyup : function (event) {
if(event.which === 13){ // Detect Enter
alert("KeyUp fired after pressing Enter");
triggerBlur = false;
}
});
Also it's preferable to use event.which rather than event.keyCode (see http://api.jquery.com/event.which/to understand why), and it is recommended to use the identity operator '===' rather than the equality '==' in javascript, as the latter is broken (see Which equals operator (== vs ===) should be used in JavaScript comparisons?)
此外,最好使用 event.which 而不是 event.keyCode(请参阅http://api.jquery.com/event.which/以了解原因),并且建议使用身份运算符 '===' 而不是javascript 中的等号“==”,因为后者被破坏(请参阅JavaScript 比较中应该使用哪个等于运算符 (== vs ===)?)