如何强制在 jQuery 中的表单中失去所有字段的焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16779247/
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
How to force to lose focus of all fields in a form in jQuery
提问by Jilco Tigchelaar
When a input field changes (onchange) I trigger a function to set a variable. The only problem is that the field first has to lose focus before the variable is set and I can check if the field(s) is changed, this is what I want to do when the user clicks on a tab so I can check if the user is forgotten to submit his form in the previous tab. Ho to force lose focus of all possible fields, so first the onchange
event can take place?
当输入字段更改 (onchange) 时,我会触发一个函数来设置变量。唯一的问题是该字段在设置变量之前首先必须失去焦点,我可以检查该字段是否已更改,这是我在用户单击选项卡时想要执行的操作,以便我可以检查用户忘记在上一个选项卡中提交他的表单。何强迫失去所有可能的领域的焦点,所以首先onchange
可以发生事件?
回答by Karl-André Gagnon
You can use this :
你可以使用这个:
$(':focus').blur()
If you don't have jQuery in your site, you can replace it by :
如果您的站点中没有 jQuery,则可以将其替换为:
let el = document.querySelector( ':focus' );
if( el ) el.blur();
回答by WoodrowShigeru
You don't need jQuery for this; vanillaJS can do this, too.
为此,您不需要 jQuery;vanillaJS 也可以做到这一点。
document.activeElement.blur();
document.activeElement.blur();
Note: Usually, I would check for null-ness before calling a method, but activeElement
will only ever return null if there is no ?body?
node, so this direct call is pretty safe.
注意:通常,我会在调用方法之前检查空性,但activeElement
只有在没有?body?
节点时才会返回空值,因此这种直接调用非常安全。
回答by frenchie
You can trigger a .blur()
event
你可以触发一个.blur()
事件
$('SomeElement').blur(function () {
// do whatever
});
$('SomeElement').blur();