我正在使用 html5 的 localStorage API。
该场景是用户单击“添加到我的列表”按钮,以便她可以将位置名称保存到列表中。
以下代码仅在 Chrome 中完美运行。适用于一个窗口,也适用于从同一源打开两个或多个窗口的情况。 如果 Firefox 和 IE 中仅打开一个窗口,则工作正常。如果有多个窗口,则在 IE 中获取不到数据。在 Firefox 中,如果我单击添加名称,则会添加大约 30 次。
我尝试根据我找到的示例来实现我的代码。
如何解决这个问题?
提前致谢。
<input type="button" value="Add to my list" onClick="savepoi(document.getElementById('name').innerHTML);"/>
<script>
//listen if a storage happened to another window and call the right function
if (window.attachEvent) { // IE8 support
window.attachEvent('onstorage', storageEvent);}
else
{window.addEventListener('storage', storageEvent, true);}
function storageEvent(event) {
//if something is added
if(event.oldValue==null)
{savepoib(event.newValue);}
}
function savepoi(a){
//if no localStorage, set firs key=1, else add 1 to the existing
//save key and name together
if(localStorage.length==0)
{localStorage.setItem(1,1+"-"+a);}
else
{localStorage.setItem((localStorage.length+1),(localStorage.length+1)+"-"+a);}
}
function savepoib(a){
//split to get key and name
var b =a.split("-");
var idi=b[0];//key
var myname = b[1];//name
if(localStorage.length==0)
{localStorage.setItem(1,1+"-"+myname);}
else
{localStorage.setItem(idi,idi+"-"+myname);}
}
</script>
最佳答案
存储事件一团糟。我已经用它做了一些工作,但事情并不一致。 Chrome 只在其他窗口中触发事件,Firefox 在所有窗口中触发,包括发生更改的窗口,而 IE,我不记得出了什么问题。不管怎样,这是我用来消除差异的代码(它是我的 store2.js 库的插件):
https://github.com/nbubna/store/blob/master/src/store.bind.js
希望有帮助。
仅供引用,为了保持一致的行为,我考虑过尝试使用 postMessage 或类似的东西来伪造存储事件,但我从来没有时间去追寻这个想法并看看它是否真的可行。
关于javascript - localStorage无法传输数据,不适用于所有浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504186/