Javascript 离开输入字段后调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38791919/
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
Call a function after leaving input field
提问by hammerabi
On a contact form, I have several input fields. One of those fields, is an email address field:
在联系表单上,我有几个输入字段。其中一个字段是电子邮件地址字段:
<input type='text' name='input_email' onChange={this.validateEmail}/>
Right now, I have the email validation function set to the onChange attribute. Thus, while the user is entering characters into the email field, an error message appears the whole time.
现在,我将电子邮件验证功能设置为 onChange 属性。因此,当用户在电子邮件字段中输入字符时,始终会出现错误消息。
I want to change this, so that this.validateEmail
only gets called once when the user leaves that specific input field. How would I accomplish this?
我想改变这一点,以便this.validateEmail
在用户离开该特定输入字段时只调用一次。我将如何做到这一点?
I can't find any default object events that would solve this issue.
我找不到任何可以解决此问题的默认对象事件。
FYI, using ReactJS
仅供参考,使用 ReactJS
回答by Aleksandar ?oki?
You can use onblur()
or onfocusout()
. It will call function once you click out of that text field.
您可以使用onblur()
或onfocusout()
。单击该文本字段后,它将调用函数。
Example:
例子:
function myFunction() {
var x = document.getElementById("sometext");
x.value = x.value.toUpperCase();
}
<input type="text" id="sometext" onfocusout="myFunction()">
回答by Nnabugwu Michael Uchechukwu
Note: As from React 16, onFocusIn and onFocusOut have been replaced by onFocus and onBlur respectively. Hence you now have:
注意:从 React 16 开始,onFocusIn 和 onFocusOut 分别被 onFocus 和 onBlur 取代。因此,您现在拥有:
<input type='text' name='input_email' onBlur={this.validateEmail}/>
回答by Mudassar045
If you want to use jQuery then
如果你想使用 jQuery 那么
jQuery .focusout(handler)method would be enough. This method is a shortcut for .on("focusout", handler)when passed arguments, and .trigger("focusout")when no arguments are passed. Here handleris a function that execute each time the event is triggered. For example
jQuery .focusout(handler)方法就足够了。此方法是传递参数时.on("focusout", handler)和不传递参数时.trigger("focusout")的快捷方式。这里的处理程序是每次触发事件时执行的函数。例如
$("input[name="input_email"]").focusout(function(){
alert("I left the field");
});
OR
或者
$("#input_email").focusout(function(){
alert("I left the field");
});
Difference between .focusout()and .blur():
区别.focusout()和.blur() :
The focusoutevent is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blurevent in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
所述事件的内容的事件被发送到一个元素时,它,或它的任何元素内,失去焦点。这与blur事件不同,因为它支持检测后代元素的焦点丢失(换句话说,它支持事件冒泡)。