简体   繁体   English

如何使用 Javascript 监听特定键的值变化?

[英]How to listen a specific key on value change with Javascript?

is there a way to listen value change for specific key?有没有办法监听特定键的值变化? With below given code I get a window alert eachtime there is a change in local storage it works well but what i am looking for to add a event listener just for key: "Data".使用下面给定的代码,每次本地存储发生更改时,我都会收到 window 警报,它运行良好,但我正在寻找仅针对键添加事件侦听器:“数据”。

<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>

https://codepen.io/rahman23/pen/KKdyGOw https://codepen.io/rahman23/pen/KKdyGOw

The storage event tells you what key changed via its key property, so you can use that to decide whether to do your alert : storage事件通过其key属性告诉您更改了哪些键,因此您可以使用它来决定是否发出alert

window.addEventListener('storage', function(e) {  
    if (e.key === "Data") {
        alert('Woohoo, someone changed my localstorage!');
    }
});

Note that the event will only be fired if the value is changed in a different window, not the same window.请注意,只有在不同的 window 中更改值时才会触发该事件,而不是相同的 window。 (I assume you know this, as you said you were getting the alert .) If you ran your page in two tabs, for instance, clicking your buttons in one tab would cause the event in the other, but not in the one where you clicked the button. (我假设您知道这一点,正如您所说的那样您收到了alert 。)例如,如果您在两个选项卡中运行您的页面,单击一个选项卡中的按钮会在另一个选项卡中引发事件,但不会在您所在的选项卡中引发事件点击按钮。

In a comment you said you wanted to get notifications from changes made by the same window.在评论中,您说您希望从同一 window 所做的更改中获取通知。 The only way to do that is to write a wrapper function for setItem and call your handler directly, something like this:唯一的方法是为 setItem 编写一个包装器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
    });
}

If you change your button handlers to use those functions, you get notifications both for changes made in the window and for changes made in other windows.如果您更改按钮处理程序以使用这些功能,您将收到有关 window 中所做更改和其他 windows 中所做更改的通知。

Live example on JSBin (which is one of the few that lets us use local storage). JSBin 上的实时示例(这是少数让我们使用本地存储的示例之一)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM