H5 localstorage

WUSO01
  • 245

图片描述图中左边的的input的val值为对应下标th列的宽度,可以手动调节,但是调节过后怎么存储他们的值,这样下次登陆(或者刷新)这个界面就是上一次设置好的值。

回复
阅读 2.4k
4 个回答
✓ 已被采纳

谢邀~

这个还没解决吗?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="jquery.min.js"></script>
  <style>
    .item{
      background: green;
      color: white;
      height: 50px;
      width: 50px;
      display: inline-block;
      text-align: center;
      line-height: 50px;
    }
  </style>
</head>
<body>
  <div id="test">

  </div>
  <input type="text" class="itemInput" id="name0" />
  <input type="text" class="itemInput" id="name1" />
  <input type="text" class="itemInput" id="name2" />
  <input type="text" class="itemInput" id="name3" />
  <button onclick="setItemFun()">点我保存</button>
  <script>
    var localStorage = window.localStorage;
    var arrKey = ["name0", "name1", "name2", "name3"];
    function checkLocal(){
      if(localStorage.getItem(arrKey[0])){
        for (var i = 0; i < arrKey.length; i++) {
          var tempvalue = localStorage.getItem(arrKey[i])
          $("#test").append("<div class='item'>" + tempvalue + "</div>");
          $(".itemInput").eq(i).val(tempvalue);
        }
      }
    }
    function setItemFun(){
      for(var i = 0; i < $(".itemInput").length; i ++){
        localStorage.setItem("name" + i, $(".itemInput").eq(i).val())
      }
    }
    $(function(){
      checkLocal();
    });
  </script>
</body>
</html>
localStorage.setItem(key, value)
localStorage.getItem(key)
let save = (keyname,obj) => localStorage.setItem(keyname, JSON.stringify(obj));
let load = (keyname) => JSON.parse(localStorage.getItem(keyname));

需要注意的是localstorage默认读取出来是字符串,需要转换为Javascript对象。

宣传栏