HTML5 Web Storage

本篇文章仅为个人随笔,方便日后查阅,不提供任何解释。

sessionStorage 保存数据

使用这种方法保存的数据会在浏览器关闭之后全部消失,关键 JS 代码如下所示

function saveData(id) {

    var target = document.getElementById(id);
    var data = target.value;
    sessionStorage.setItem("message", data);
}

function loadData(id) {

    var target = document.getElementById(id);
    var data = sessionStorage.getItem("message");
    target.innerHTML = data;
}

可见这是一种键值对的保存方式,如同 Java 中的 map

Web Storage 保存数据

这种方式保存的数据会永久存在,也就是说即使关闭了浏览器,在下次打开浏览器的时候,保存的数据会仍然存在。关键 JS 代码如下所示

function saveData(id) {
    var target = document.getElementById(id);
    var data = target.value;
    localStorage.setItem("message", data);
}

function loadData(id) {
    var target = document.getElementById(id);
    var data = localStorage.getItem("message");
    target.innerHTML = data;
}

使用 Web Storage 实现简易留言板

function saveData(id) {
    var target = document.getElementById(id);
    var data = target.value;
    var time = new Date().getTime();
    localStorage.setItem(time, data);
    alert("Save Success !");
    loadData('msg')
}

function loadData(id) {

    var result = "";
    for (var i = 0; i < localStorage.length; i++) {
        var key = localStorage.key(i);
        var data = localStorage.getItem(key);
        var time = new Date();
        time.setTime(key);
        result += ">";
    }
    result += "
" + data + "" + time + "
"; var target = document.getElementById(id); target.innerHTML = result; } function clearData() { localStorage.clear(); alert("Delete Success !"); loadData('msg'); }

模拟数据库

function saveData() {
    var data = new Object();

    data.name = document.getElementById("name").value;
    data.email = document.getElementById("email").value;
    data.tel = document.getElementById("tel").value;
    data.address = document.getElementById("address").value;

    var str = JSON.stringify(data);
    localStorage.setItem(data.name, str);
    alert("Save Success !");
}

function findData(id) {

    var find = document.getElementById("find").value;
    var str = localStorage.getItem(find);
    var data = JSON.parse(str);

    var result = "姓名 : " + data.name + "
"; result += "电话 : " + data.tel + "
"; result += "Email : " + data.email + "
"; result += "地址 : " + data.address + "
"; var target = document.getElementById(id); target.innerHTML = result; }

HTML5 编码




    
    Title
    >




        >
        
        >
    
姓名
电话
Email
地址

你可能感兴趣的:(个人随笔)