如何使用 jQuery 将函数绑定(bind)到 HTML5 localStorage 更改事件?
$(function () {
$(window).bind('storage', function (e) {
alert('storage changed');
});
localStorage.setItem('a', 'test');
});
我已尝试上述方法,但未显示警报。
更新:它在 Firefox 3.6 中有效,但在 Chrome 8 或 IE 8 中无效,因此问题应该更多“如何使用 jQuery 为所有浏览器绑定(bind)到 localStorage 更改事件?”
最佳答案
事实证明,这实际上工作正常,我误解了 the specification
When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a local storage area, if the methods did something, then in every Document object whose Window object's localStorage attribute's Storage object is associated with the same storage area, other than x, a storage event must be fired
换句话说,除了更新 localStorage
对象并引发事件的窗口/选项卡外,每个窗口/选项卡都会触发一个存储事件。
所以事件没有被触发,因为我只打开了一个窗口/标签。如果我将上面的代码放在一个页面中并在两个选项卡中打开该页面,我会看到在第二个选项卡中触发的事件。
This answer on the problem 包含更多详细信息。
关于jquery - 如何为所有浏览器使用 jQuery 绑定(bind)到 localStorage 更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4671852/