work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Phonegap下localStorage使用实践

Posted on 2017-04-01 15:38  work hard work smart  阅读(501)  评论(0编辑  收藏  举报

HTML5的Web Storage API提供了两种客户端存储数据的方法

localStorage和sessionStorage。 localStorage没有时间限制,程序升级也不会消失,可以满足持久化需求。

设置localStorage的方法

 window.localStorage.setItem("likecolor","red");

获得localStorage的方法

window.localStorage.getItem("likecolor");

完整的Code如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
    <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css">
    <script type="text/javascript" src="js/jquery.js"></script>
    <script  type="text/javascript" src="js/jquery.mobile-1.4.5.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="cordova.js" ></script>
    <title>Hello World</title>

    <script type="text/javascript" charset="utf-8">
        document.addEventListener('deviceready', onDeviceReady, false);
        function onDeviceReady(){
             $(".localStorageBtn").bind("click",function(event,ui){
                  setLocalStorage();
             });

             $(".showLocalStorageBtn").bind("click", function(event, ui ) {
                  getLocalStorage();
             });
        }

         function setLocalStorage(){
            window.localStorage.setItem("likecolor","red");
         }

         function getLocalStorage(){
             var item = window.localStorage.getItem("likecolor");
             var info = document.getElementById("info");
             info.innerHTML = item;
         }
    </script>
</head>

<body>
<div id="page1" data-role="page" data-add-back-btn="true">
    <header data-role="header"><h1>Head</h1></header>
    <div data-role="content">
        <a data-role="button" class="localStorageBtn">set Local Storage</a>
        <a data-role="button" class="showLocalStorageBtn">get Local Storage</a>
        <p id="info"/>
    </div>
    <footer data-role="footer"><h1>Footer</h1></footer>
</div>

</body>

</html>