如何将用户的多个输入存储到localStorage?

时间:2018-04-09 17:12:07

标签: javascript arrays json local-storage

所以我有一个输入字段,要求用户输入一个数字:

<label for="amount"><b>Amount</b></label>
<input type="text" placeholder="Enter Number" name="number" id="number" required>   

我想要做的是将其存储在localStorage中: 这是我的剧本:

var number = document.getElementById('number').value;
var aNumber = [];
aNumber.push(number);
localStorage.setItem('number',JSON.stringify(aNumber));

然而,当用户输入新值时,它会覆盖旧值。因此始终只存储一个值。 我希望它能存储所有值。

提前致谢。

3 个答案:

答案 0 :(得分:1)

它会覆盖,因为你总是在创建一个新数组,而不是使用旧数组(如果它存在)。您需要按如下方式更改代码:

var aNumber = !!localStorage.getItem('number') ? JSON.parse(localStorage.getItem('number')) : [];
var number = document.getElementById('number').value;
aNumber.push(number);
localStorage.setItem('number', JSON.stringify(aNumber));

上面的代码首先检查数组是否存在,如果存在,则代码使用相同的数组,否则创建一个新数组。

PS:由于JSON.parseJSON.stringify方法的重复执行,此代码最终会变得太慢,因为数组中的项数会增加。

答案 1 :(得分:0)

这在stackoverflow中不起作用,因为localStorage已被禁用,但您可以在行动here中看到这一点:

var aNumber = [];
document.getElementById('number').addEventListener('change', function(event) { 
    var number = document.getElementById('number').value;
    aNumber.push(number);
    localStorage.setItem('number',JSON.stringify(aNumber));
    console.log(localStorage.getItem('number'));
});
<label for="amount"><b>Amount</b></label>
<input type="text" placeholder="Enter Number" name="number" id="number" required>

您很可能每次都覆盖aNumber数组。

答案 2 :(得分:0)

以下代码无法在Stack Overflow上使用,原因是阻止了本地存储的保存。这是一个小提琴,将展示这一点:https://jsfiddle.net/612s5ack/1/

<script type="text/javascript">
  var isNotBlank = function(str) {
    if (typeof str !== 'string') {
      return false;
    }
    return !(!str || /^\s*$/.test(str));
  };

  var isBoolean = function(bool) {
    return typeof bool === 'boolean';
  };

  var saveToLocalStorage = function(key, value, nullable) {

    // failsafe to make sure that default action is to prevent
    // null/undefined/blank values from being saved
    if (!isBoolean(nullable)) {
      nullable = false;
    }

    if (isNotBlank(key) === true && (nullable === true || (nullable === false && isNotBlank(value) === true))) {
      var message = null;
      // Check to see if local storage is available
      if (typeof(localStorage) === 'undefined') {
        message = 'Local Storage is not supported by this browser.';
        console.log(message);
        return message;
      } else {
        try {
          localStorage.setItem(key, value);
        } catch (exception) {
          message = 'Local Storage error occurred on save: ' + exception.message;
          console.log(message);
          return message;
        }
      }
    }
  };

  var getItemFromLocalStorage = function(key) {
    if (isNotBlank(key) === true) {
      if (typeof(localStorage) === 'undefined') {
        var message = 'Local Storage is not supported by this browser.';
        console.log(message);
        return null;
      } else {
        try {
          return localStorage.getItem(key);
        } catch (exception) {
          message = 'Local Storage error occurred on delete: ' + exception.message;
          console.log(message);
          return null;
        }
      }
    }
  };
  
  var save = function() {
    var aNumber = [];
    var number = document.getElementById('number').value;
    var localStorageSaved = getItemFromLocalStorage('number');
    if (localStorageSaved !== null) {
      aNumber = JSON.parse(localStorageSaved);
    }
    aNumber.push(number);
    saveToLocalStorage('number', JSON.stringify(aNumber));
  };

</script>
<label for="amount"><b>Amount</b></label>
<input type="text" placeholder="Enter Number" name="number" id="number" required/>
<input type="button" id="save" value="Save Number" onclick="save();" />