Html5 表单的LocalStorage

Posted 文恒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Html5 表单的LocalStorage相关的知识,希望对你有一定的参考价值。

html5表单的数据存储

Html5 提供localStorage方法在客户端存储数据;
优点:没有时间限制的数据(存储一年之后,数据依然可用);
实现:用javascript来存储和访问数据

例子(来自《Head First Html5》):

该要:生成一个表单(form),实现添加歌曲与Web存储加载;

基本用法解析:

1.获取localStorage的长度:localStorage.length
2.添加/编辑localStorage的内容:localStorage.setItem(键,值);
3.根据对应的索引去获取对应:localStorage的key的值:localStorage.key(索引);
4.根据对应的key获取对应的:localStorage.getItem(key);
5.删除数据:localStorage.removeItem(key);

1、建立一个播放列表的表单(index.html)

//index.html

<!doctype html>
<html lang = "en">
<head>
    <title>Webville Tunes</title>
    <meta charset="utf-8">
    <script src="playlist_store.js"></script>
    <script src="playlist.js"></script>
    <link rel="stylesheet" href="playlist.css">
</head>
<body>
    <form>
        <input type="text" id="songTextInput" size="40" placeholder="Song name">
        <input type="button" id="addButton" value="Add Song">
    </form>
    <ul id="playlist">
    </ul>
</body>
</html>

2、Button的事件响应(playlist.js)

//playlist.js
window.onload = init;
function init() 
    var button = document.getElementById("addButton");
    button.onclick = handleButtonClick;

    loadPlaylist();

function handleButtonClick() 
    var textInput = document.getElementById("songTextInput");
    var songName = textInput.value;

    if (songName == "")
        alert("Please enter a song");
    else 
        var li = document.createElement("li");
        li.innerHTML = songName;
        var ul = document.getElementById("playlist");
        ul.appendChild(li);
        save(songName);
       

3、播放列表的存储与加载(playlist_store.js)

//playlist_store.js

//保存播放列表
function save(item) 
    var playlistArray = getStoreArray("playlist");
    playlistArray.push(item);
    localStorage.setItem("playlist", JSON.stringify(playlistArray));


//加载本地的播放列表playlist
function loadPlaylist() 
    var playlistArray = getSavedSongs();
    var ul = document.getElementById("playlist");

    if (playlistArray != null) 
        for (var i = 0; i < playlistArray.length; i++) 
            var li = document.createElement("li");
            li.innerHTML = playlistArray[i];
            ul.appendChild(li);
        
    


//获取被保存的歌曲
function getSavedSongs() 
    return getStoreArray("playlist");


//创建数组
function getStoreArray(key) 
    var playlistArray = localStorage.getItem(key);
    if (playlistArray == null || playlistArray == "") 
        playlistArray = new Array();
    
    else 
        playlistArray = JSON.parse(playlistArray);
    
    return playlistArray;

以上是关于Html5 表单的LocalStorage的主要内容,如果未能解决你的问题,请参考以下文章

[html5]localStorage的原理和HTML5本地存储安全性

html5 localstorage 怎么取存储条数

html5 localstorage能存多少

HTML5 localStorage 有用的函数 // JavaScript,TypeScript [关闭]

html5的localstorage详解

android html5 localstorage某手机从localstorage中取不到数据