您并没有真正说明您是在尝试跟踪用户对输入元素的更改还是程序更改。对于新的浏览器,您可以监视input
事件,它会告诉您输入字段的值何时被用户控制更改。除了挂钩所有可能更改它的代码以添加您自己的通知系统可能已应用更改之外,没有跨浏览器方法可以判断字段的值是否已以编程方式更改。
我不久前编写了这个跨浏览器函数来监视所有不同形式的用户对所有浏览器输入字段的更改。这段代码恰好是 jQuery 方法的形式,但是可以很容易地将逻辑修改为纯 javascript。此代码检查是否支持新事件。如果是这样,它会使用它们。如果没有,它会挂接许多其他事件来尝试捕获用户更改字段的所有可能方式(拖放、复制/粘贴、键入等)。
(function($) {
var isIE = false;
// conditional compilation which tells us if this is IE
/*@cc_on
isIE = true;
@*/
// Events to monitor if 'input' event is not supported
// The boolean value is whether we have to
// re-check after the event with a setTimeout()
var events = [
"keyup", false,
"blur", false,
"focus", false,
"drop", true,
"change", false,
"input", false,
"textInput", false,
"paste", true,
"cut", true,
"copy", true,
"contextmenu", true
];
// Test if the input event is supported
// It's too buggy in IE so we never rely on it in IE
if (!isIE) {
var el = document.createElement("input");
var gotInput = ("oninput" in el);
if (!gotInput) {
el.setAttribute("oninput", 'return;');
gotInput = typeof el["oninput"] == 'function';
}
el = null;
// if 'input' event is supported, then use a smaller
// set of events
if (gotInput) {
events = [
"input", false,
"textInput", false
];
}
}
$.fn.userChange = function(fn, data) {
function checkNotify(e, delay) {
var self = this;
var this$ = $(this);
if (this.value !== this$.data("priorValue")) {
this$.data("priorValue", this.value);
fn.call(this, e, data);
} else if (delay) {
// The actual data change happens aftersome events
// so we queue a check for after
// We need a copy of e for setTimeout() because the real e
// may be overwritten before the setTimeout() fires
var eCopy = $.extend({}, e);
setTimeout(function() {checkNotify.call(self, eCopy, false)}, 1);
}
}
// hook up event handlers for each item in this jQuery object
// and remember initial value
this.each(function() {
var this$ = $(this).data("priorValue", this.value);
for (var i = 0; i < events.length; i+=2) {
(function(i) {
this$.on(events[i], function(e) {
checkNotify.call(this, e, events[i+1]);
});
})(i);
}
});
}
})(jQuery);