html5-localstorage操作(小demo)


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
head>
<body>
    <form action="get">
        <label for="name">姓名:label>
        <input type="text" id="name">
        <br>
        <label for="mobilephone">手机号:label>
        <input type="text" id="mobilephone">
        <br>
        <input type="button" id="add" value="添加">
        <hr>
    form>
    <form action="get">
        <label for="search">label>
        <input type="text" id="search">
        <input type="button" value="查找姓名" id="search-name">
        <div id="showPhone">div>
    form>
    <div id="show">div>
    <script>
        //向localStorage中添加健名和值
        var userName = document.getElementById('name');
        var mobilephone = document.getElementById("mobilephone");
        var addButton = document.getElementById("add");
        addButton.addEventListener("click",function(){
            if(window.localStorage){
                localStorage.setItem(userName.value,mobilephone.value);//这里username对应的是姓名,如果是mobile对应的是该用户的手机号,放在localstorage中,以键名-键值存储
            }
        },false);

        console.log(typeof undefined);
        //寻找是否有名为name的手机号
        var searchName = document.getElementById("search-name");
        var search = document.getElementById("search");
        var showPhone= document.getElementById("showPhone");
        searchName.addEventListener('click',function(){
            if(window.localStorage){
                var local = localStorage.getItem(search.value);
                if(typeof(local)!= "undefined"){
                    var str = search.value + "的手机号是 :" + local ; 
                    showPhone.innerHTML =str; 
                }
            }
        },false);


        //将所有添加的名字和手机号输出
        var show = document.getElementById("show");
        var ulTag = document.createElement("ul");
        for(var i = 0; ivar showname = localStorage.key(i);
            var showmobile = localStorage.getItem(showname);
            var StrNew = "姓名是:"+showname+" , "+"手机号是:"+showmobile;
            var liTag = document.createElement("li");
            liTag.innerHTML = StrNew;
            ulTag.appendChild(liTag);
        }
        show.appendChild(ulTag);
    script>
body>
html>

你可能感兴趣的:(html5)