use*_*051 2 html javascript local-storage
有没有办法监听特定键的值变化?使用下面给出的代码,每当本地存储发生变化时,我都会收到一个窗口警报,它运行良好,但我正在寻找仅针对键:“数据”添加事件侦听器。
<body>
<button onClick="setData1()">Set 1</button>
<button onClick="setData2()">Set 2</button>
<button onClick="clearData()">Clear</button>
</body>
</html>
<script>
window.addEventListener('storage', function(e) {
alert('Woohoo, someone changed my localstorage!');
});
function setData1(){
console.log('SET');
localStorage.setItem('Data', '1');
}
function setData2(){
console.log('SET');
localStorage.setItem('Data', '2');
}
function clearData(){
console.log('CLEAR');
localStorage.clear()
}
</script>
Run Code Online (Sandbox Code Playgroud)
该storage事件通过其属性告诉您哪个键发生了变化key,因此您可以使用它来决定是否执行以下操作alert:
window.addEventListener('storage', function(e) {
if (e.key === "Data") {
alert('Woohoo, someone changed my localstorage!');
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,只有在不同窗口(而不是同一窗口)中更改值时才会触发该事件。(我假设您知道这一点,正如您所说的那样alert。)例如,如果您在两个选项卡中运行页面,则单击一个选项卡中的按钮将导致另一个选项卡中发生事件,但不会在您单击的选项卡中发生事件按钮。
在评论中,您说您希望从同一窗口所做的更改中获得通知。唯一的方法是编写一个包装函数setItem并直接调用您的处理程序,如下所示:
function storageChanged({key, oldValue, newValue}) {
if (key === "Data") {
const isNew = oldValue === null && newValue !== null;
console.log(`Data event, new value = "${newValue}". First time? ${isNew ? "Yes" : "No"}`);
}
}
window.addEventListener('storage', storageChanged);
function setLocalStorage(key, newValue) {
newValue = String(newValue);
const oldValue = localStorage.getItem(key);
localStorage.setItem(key, newValue);
storageChanged({
key,
oldValue,
newValue,
storageArea: localStorage,
url: window.location.url
});
}
function clearLocalStorage() {
localStorage.clear();
storageChanged({
key: null,
oldValue: null,
newValue: null,
storageArea: localStorage,
url: window.location.url
});
}
Run Code Online (Sandbox Code Playgroud)
如果您更改按钮处理程序以使用这些函数,您将收到有关窗口中所做的更改以及其他窗口中所做的更改的通知。
JSBin 上的实时示例(这是少数几个允许我们使用本地存储的示例之一)。
| 归档时间: |
|
| 查看次数: |
3618 次 |
| 最近记录: |