请注意Object.Watch https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch and Object.Observe https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe现已弃用(截至 2018 年 6 月)。
我一直在寻找一种简单的方法来监视对象或变量的更改,我发现Object.watch()
,Mozilla 浏览器支持,但 IE 不支持。所以我开始四处寻找是否有人写过某种类似的东西。
我唯一发现的是一个 jQuery 插件 http://plugins.jquery.com/watch/,但我不确定这是否是最好的方法。我当然在我的大多数项目中使用 jQuery,所以我不担心 jQuery 方面......
无论如何,问题是:有人能给我展示 jQuery 插件的工作示例吗?我在使其工作时遇到问题...
或者,有谁知道有更好的跨浏览器替代方案吗?
回答后更新:
谢谢大家的回复!我尝试了这里发布的代码:http://webreflection.blogspot.com/2009/01/internet-explorer-object-watch.html http://webreflection.blogspot.com/2009/01/internet-explorer-object-watch.html
但我似乎无法让它与 IE 一起工作。下面的代码在 Firefox 中运行良好,但在 IE 中不起作用。在 Firefox 中,每次watcher.status
被改变时,document.write()
in watcher.watch()
被调用,您可以在页面上看到输出。在 IE 中,这不会发生,但我可以看到watcher.status
正在更新值,因为最后一个document.write()
调用显示正确的值(在 IE 和 FF 中)。但是,如果回调函数没有被调用,那么这是毫无意义的......:)
我错过了什么吗?
var options = {'status': 'no status'},
watcher = createWatcher(options);
watcher.watch("status", function(prop, oldValue, newValue) {
document.write("old: " + oldValue + ", new: " + newValue + "<br>");
return newValue;
});
watcher.status = 'asdf';
watcher.status = '1234';
document.write(watcher.status + "<br>");