更改现有代码以保存到localStorage

时间:2016-04-20 11:58:53

标签: javascript jquery html5

在帮助下,我设法为我想做的事做了一个工作基础。基本上,我希望通过表单获取用户输入,保存它,然后在用户要求查看时将整个事物显示为日志。

我已经意识到信息需要存储在localStorage中。我想知道是否有一种简单的方法可以在执行功能之后将输入保存到localStorage,以及是否可以实现与从第一时刻将每个变量保存到localStorage相同的功能。

当前代码https://gist.github.com/anonymous/dad979778bdbddc87e786c837cb03634#file-logger-js

编辑:链接已更正

1 个答案:

答案 0 :(得分:1)

使用localStorage的一个简单示例如下:

HTML:

<input type="text" placeholder="something to store" id="inputString" />
<h1 onclick="clearStorage()">clear storage</h1>
<h1 onclick="saveStatusLocally()">store</h1>
<h1 onclick="readStatus()">print</h1>
<div id="write"></div>

JS:

//array to store values
var stores = Array();
//input field text
var inputField = document.getElementById('inputString');

//clear the storage
function clearStorage() {
  //clear the storage
  stores = Array();
  localStorage.clear("database");
  //visually cleared
  document.getElementById('write').innerHTML = "storage cleared.";
}

// save the string
function saveStatusLocally() {
  //grab the value of the text box
  var stringToSave = inputField.value;
  if ((stringToSave == null) || (stringToSave == "")) {
    document.getElementById('write').innerHTML = "nothing to store.";
  } else {
    //push that value to the array
    stores.push(stringToSave);
    //clear the input field for visual 
    inputField.value = "";
    //print that value into the local storage named database and joing by a non-breaking space
    window.localStorage.setItem("database", stores.join(" "));
    //confirm write
    document.getElementById('write').innerHTML = "data stored.";
    //clear message after 1s
    setTimeout(function() {
      document.getElementById('write').innerHTML = "";
    }, 1000);

  }
}

// read the string
function readStatus() {
  //print the value of the local storage "database" key
  if (window.localStorage.getItem("database") == null) {
    document.getElementById('write').innerHTML = "nothing stored.";
  } else {
    document.getElementById('write').innerHTML = window.localStorage.getItem("database");
  }
}

Js Fiddle:https://jsfiddle.net/nikdtu/a180mt5c/