浏览器自动填充和 Javascript 触发事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4938242/
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
Browser Autofill and Javascript triggered events
提问by Glen Solsberry
One of our users just brought up the fact that their browsers Autofill doesn't cause JS onChange events to fire; this causes a problem with user registration for us.
我们的一位用户刚刚提出这样一个事实,即他们的浏览器自动填充不会导致 JS onChange 事件触发;这会导致我们的用户注册出现问题。
Is this by design? Is there a way to work around it?
这是故意的吗?有没有办法解决它?
采纳答案by jishi
One solution I have been using occasionally is to check whether the value of the field/input/select differs from it's defaultValue. defaultValue would be the value that was originally in the markup, and value is the current value aka selected or entered value. This would probably differ even though the form was autopopulated.
我偶尔使用的一种解决方案是检查字段/输入/选择的值是否与其默认值不同。defaultValue 将是最初在标记中的值,而 value 是当前值,也就是选择或输入的值。即使表单是自动填充的,这也可能会有所不同。
If you want to turn off autofill altogether, it might be wise to add autocomplete="off" on fields that are directly connected to your logic.
如果您想完全关闭自动填充,在直接连接到您的逻辑的字段上添加 autocomplete="off" 可能是明智的。
回答by Lavlesh Mishra
If you want to get the autofill behaviour but change the styling, maybe you can do something like this (jQuery):
如果您想获得自动填充行为但更改样式,也许您可以执行以下操作 ( jQuery):
$(window).load(function(){
if($('input:-webkit-autofill')){
$('input:-webkit-autofill').each(function(){
//put your conditions here
});
// RE-INITIALIZE VARIABLES HERE IF YOU SET JQUERY OBJECT'S TO VAR FOR FASTER PROCESSING
}});
回答by LcSalazar
Just in case someone is still looking for a solution (just as I was today), to listen to a browser autofill change, here's a custom jquery method that I've built, just to simplify the proccess when adding a change listener to an input:
以防万一有人仍在寻找解决方案(就像我今天一样),要收听浏览器自动填充更改,这是我构建的自定义 jquery 方法,只是为了简化向输入添加更改侦听器时的过程:
$.fn.allchange = function (callback) {
var me = this;
var last = "";
var infunc = function () {
var text = $(me).val();
if (text != last) {
last = text;
callback();
}
setTimeout(infunc, 100);
}
setTimeout(infunc, 100);
};
You can call it like this:
你可以这样称呼它:
$("#myInput").allchange(function () {
alert("change!");
});
回答by Satyajit
Have you tried using the onpropertychanged instead of onchange event? That's for IE only though and is the recommended fix on MSDN.
您是否尝试过使用 onpropertychanged 而不是 onchange 事件?这仅适用于 IE,并且是 MSDN 上推荐的修复程序。
回答by user2048344
Here's a pretty good solution that does something similar to what jishi described:
这是一个非常好的解决方案,它的作用类似于jishi所描述的:
Updated the broken link with Wayback Machine link
使用 Wayback Machine 链接更新了断开的链接

