localStorage eventHandler不会被调用 [英] localStorage eventHandler Doesn't Get Called

查看:72
本文介绍了localStorage eventHandler不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码:

 < script type =text / javascript> 
函数getLocalStorage(){
尝试{
if(!! window.localStorage)return window.localStorage;
} catch(e){
return undefined;



函数getAddEventListener(){
尝试{
if(!! window.addEventListener)return window.addEventListener;
} catch(e){
return undefined;



function eventHandler(e){
alert(here we are =+ e.storageArea.traveler);


函数testStorage(){
var db = getLocalStorage();
var addEL = getAddEventListener();

if(addEL){
addEL('storage',eventHandler,false);
} else {
alert('这个浏览器不支持事件监听器');
}

db.setItem('traveler','Bill');
db.setItem('destination','Ventura');
db.setItem('transportation','Airplane');

document.getElementById('results')。innerHTML = db.getItem('destination');
}
< / script>

< / head>

< body onload =testStorage();>
< div id =results> < / DIV>
< / body>

< / html>

它成功地将项目插入本地存储并显示结果'results'-element,但eventHandler doesn没有工作。我刷新浏览器窗口并没有看到任何警报消息。为什么?

解决方案

因为存储事件不适用于相同的窗口/选项卡。它们仅被用于其他使用相同 localStorage 的窗口/选项卡。尝试打开两个分隔标签,并在一个插入一些数据到 localStorage

以下是一个类似的问题 a>,它解释了 localStorage 事件是如何工作的。


Here is my code:

<script type="text/javascript">
    function getLocalStorage() {
        try {
            if (!! window.localStorage) return window.localStorage;
        } catch(e) {
            return undefined;
        }
    }

    function getAddEventListener() {
        try {
            if( !! window.addEventListener ) return window.addEventListener;
        } catch(e) {
            return undefined;
        }
    }

    function eventHandler(e) {
        alert("here we are = " + e.storageArea.traveler);
    }       

    function testStorage() {    
        var db = getLocalStorage();
        var addEL = getAddEventListener();

        if(addEL) {
          addEL('storage', eventHandler, false);
        } else {
            alert('This browser does not support event listeners');
        }

        db.setItem('traveler', 'Bill');
        db.setItem('destination', 'Ventura');
        db.setItem('transportation', 'Airplane');

        document.getElementById('results').innerHTML = db.getItem('destination');
    }   
</script>

</head>

<body onload="testStorage();">
  <div id="results"> </div>
</body>

</html>

It successfully insert items in the local storage and display result in 'results'-element, but eventHandler doesn't work. I refresh the browser windows and don't see any alert messages. Why?

解决方案

Because storage events don't work for same window/tab. They are fired only for other windows/tabs that use same localStorage. Try opening two separat tabs and in one insert some data to the localStorage.

Here is a similar question that explains how localStorage event works.

这篇关于localStorage eventHandler不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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