Cross-browser localStorage

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 20:16:11

问题


i imagined a todo list written in plain JS without using framework just to see the localStorage cross-browser compatibility.

The script is

function addText(){
var input = document.getElementById('input').value;
date = new Date();
var time = date.getTime();
if (input !== "") {
    localStorage.setItem(time,"lalala");
    document.getElementById('input').value = '';
}};

function loadText(){
if (window.localStorage) {
        for(var i in window.localStorage){
            console.log(i+"--------theiiiiiii");
            var z = localStorage.getItem(i);
            console.log(z+"--------you keep me satisfied");
    }
} else {
    alert("Your Browser does not support LocalStorage.");
}
}

Now, i Chrome works, in Firefox almost, in opera i get set values plus all the localStorage operators. Does anybody know a solution to this?

1381311087810--------theiiiiiii
lalala--------you keep me satisfied
length--------theiiiiiii
null--------you keep me satisfied
key--------theiiiiiii
null--------you keep me satisfied
getItem--------theiiiiiii
null--------you keep me satisfied
setItem--------theiiiiiii
null--------you keep me satisfied
removeItem--------theiiiiiii
null--------you keep me satisfied
clear--------theiiiiiii
null--------you keep me satisfied

回答1:


Try by listing only the keys:

function loadText(){
    if (window.localStorage) {

        /// list all keys from object
        var keys = Object.keys(localStorage);

        for(var i, key; key = keys[i]; i++) {
            console.log(key + "--------theiiiiiii");
            var z = localStorage.getItem(key);
            console.log(z + "--------you keep me satisfied");
        }
    } else {
        alert("Your Browser does not support LocalStorage.");
    }
}


来源:https://stackoverflow.com/questions/19268459/cross-browser-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!