如何使用 jQuery 为所有浏览器绑定到 localStorage 更改事件? [英] How to bind to localStorage change event using jQuery for all browsers?

查看:22
本文介绍了如何使用 jQuery 为所有浏览器绑定到 localStorage 更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 jQuery 将函数绑定到 HTML5 localStorage 更改事件?

$(function () {$(window).bind('storage', function (e) {alert('存储已更改');});localStorage.setItem('a', 'test');});

我已经尝试了上述方法,但没有显示警报.

更新:它适用于 Firefox 3.6,但不适用于 Chrome 8 或 IE 8,所以问题应该更多是如何使用 jQuery 为所有浏览器绑定到 localStorage 更改事件?"

解决方案

事实证明这实际上工作正常,我误解了 规范

<块引用>

当 setItem()、removeItem() 和 clear() 方法在与本地存储区域关联的 Storage 对象 x 上被调用时,如果这些方法做了某事,那么在其 Window 对象的 localStorage 属性的每个 Document 对象中存储对象关联同一个存储区域,除了x,必须触发存储事件

换句话说,除了更新 localStorage 对象并引发该事件的窗口/标签外,每个窗口/标签都会触发存储事件.

所以事件没有被触发,因为我只打开了一个窗口/选项卡.如果我将上述代码放在一个页面中并在两个选项卡中打开该页面,我会看到在第二个选项卡中触发的事件.

这个问题的答案包含更多细节.>

How do I bind a function to the HTML5 localStorage change event using jQuery?

$(function () {

  $(window).bind('storage', function (e) {
    alert('storage changed');
  });

  localStorage.setItem('a', 'test');

});

I've tried the above but the alert is not showing.

Update: It works in Firefox 3.6 but it doesn't work in Chrome 8 or IE 8 so the question should be more 'How to bind to localStorage change event using jQuery for all browsers?'

解决方案

It turns out that this is actually working correctly and I have misinterpreted 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

In other words, a storage event is fired on every window/tab except for the one that updated the localStorage object and caused the event.

So the event was not fired because I only had one window/tab open. If I place the above code in a page and open the page in two tabs I would see the event fired in the second tab.

This answer on the problem contains more details.

这篇关于如何使用 jQuery 为所有浏览器绑定到 localStorage 更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆