gpt4 book ai didi

jquery - 仅监听 localStorage.removeItem() 事件

转载 作者:行者123 更新时间:2023-12-03 22:50:14 26 4
gpt4 key购买 nike

我正在使用 pnotify 插件向用户显示通知。但是,如果用户通过单击 X 图标关闭 1 个选项卡中的通知,我想删除所有选项卡上的通知。

我为此使用本地存储,每次向用户显示新通知时,它都会添加到本地存储中。当用户按下 X 图标时,我执行 localStorage.removeItem(key)。如何监听此事件以关闭所有选项卡中的通知?

我的听众如下:

$(window).bind('storage', function(e) {
// if it was removed
if (e.originalEvent.newValue == null) {
var notificationObject = e.originalEvent.oldValue;

// call remove function on pnotify object
notificationObject.remove();
}
});

我注意到,如果 newValue 被删除,它就会变成 null,理论上这会起作用(尚未测试),但是如果在该项目上调用removeItem,它总是返回 null 吗?如果项目值更改为 null,那么由于值更改正确,它会触发该事件吗?

最佳答案

本地存储将所有内容存储为字符串。

localStorage.setItem("foo", null);

// returns "null"
localStorage.getItem("foo");

事实上,newValue 在被删除时为 nullMDN: StorageEvent说:

The new value of the key. The newValue is null when the change has been invoked by storage clear() method or the key has been removed from the storage. Read only.

因此,使用 === null 检查 null 是安全的。

关于jquery - 仅监听 localStorage.removeItem() 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34888036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com