jQuery:对浏览器自动填充做出反应 [英] jQuery: react to form auto-filling by browser
问题描述
我有两个表单元素,一个电子邮件
和一个密码
。只有在电子邮件
元素中输入了某些内容时,才能显示密码
元素。也就是说,只有电子邮件
不为空。
I have two form elements, a email
and a password
. The password
element must only be shown if something has been entered in the email
element. That is, only if email
is not empty.
<input id="email" name="email" onblur="if (jQuery("#email").val() === "") { jQuery("#password").hide(); } else { jQuery("#password").show(); }" onchange="if (jQuery("#email").val() === "") { jQuery("#password").hide(); } else { jQuery("#password").show(); }" onfocus="if (jQuery("#email").val() === "") { jQuery("#password").hide(); } else { jQuery("#password").show(); }" placeholder="Email" style="width:360px;height:28px;margin-bottom:0px;" type="text">
如您所见,我正在处理三个事件:
As you see I am handling three events:
- onfocus:当焦点进入电子邮件元素时我会做出反应
- onblur:这样当焦点离开电子邮件元素时我会做出反应
- onchange:以便我在电子邮件元素更改时做出反应
实际上,我只想运行电子邮件更改时的脚本。我不关心焦点,但我无法处理一般的更改事件。
Actually, I only want to run the script whenever the email changes. I do not care about focus, but I am unable to handle a generic change event.
此外,这是我的主要问题,我无法对此做出反应浏览器自动填充表单时生成的事件。有这样的事件吗?我该如何处理?
Besides, and this is my main problem, I am not able to react to the the event generated when the browser is auto-filling the form. Is there such an event? How can I handle it?
推荐答案
初始页面渲染时会发生浏览器自动填充。您是否尝试在onReady回调中检查字段?请注意,此事件仅由Jquery等更高级别的实现提供,而不是由浏览器直接提供。
Browser auto-filling occurs on initial page rendering. Have you tried checking the field in an "onReady" callback? Note that this event is only provided by higher level implementations like Jquery, not directly by the browser.
ready使用jquery回调 :(更新以反映评论)
Example of "ready" callback with jquery: (updated to reflect the comments)
$(function() {
setTimeout(function() {
$("#email").trigger('change');
}, 200);
});
还有一篇文章解释自己动手: http://dustindiaz.com/smallest-domready-ever
There is also an article explaining the "do it yourself way": http://dustindiaz.com/smallest-domready-ever
这篇关于jQuery:对浏览器自动填充做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!