如何在发送到localstorage之前组合复选框值?

时间:2018-04-15 06:21:15

标签: javascript arrays json local-storage

我希望存储 localStorage 复选框的值,并带有空格分隔符。 当我检查A B 并按下保存按钮时,会将其另存为

["A","B"]

如果我检查A,B和C并按下按钮,则阵列变为

["A","B","A","B","C"]

我想要获得的输出应该是

["A B","A B C"]

所以这是我的代码:

<body>
    <div class="container">
        <input type="checkbox" class="checks" value="A"> A<br>
        <input type="checkbox" class="checks" value="B"> B<br>
        <input type="checkbox" class="checks" value="C"> C<br>
        <br><br>
        <a href="#" onclick="getValue();return false;">Get Value</a>

        <script>
            function getValue() {
            var myArray = !!localStorage.getItem('str') ? JSON.parse(localStorage.getItem('str')): [];
            var checks = document.querySelectorAll('.checks:checked');

            if(!checks.length) return; 

            for (i = 0; i < checks.length; i++) {
            myArray.push(checks[i].value);
            }
            localStorage.setItem('str',JSON.stringify(myArray));
            console.log('str', myArray.join(' '));

            }

        </script>
    </div>
</body>

2 个答案:

答案 0 :(得分:0)

在将阵列保存到本地存储之前,您无法加入阵列。

答案 1 :(得分:0)

在新阵列中收集当前答案(演示中为myChecks),并在保存到myArray之前将其添加到localStorage

注意: stackoverflow的代码段阻止了localStorage的使用。我已经评论了使用localStorage的行,并且我使用外部myArray变量进行了演示。要在代码中使用,请取消注释读取和写入localStorage的行,并删除var myArray = []

&#13;
&#13;
var myArray = []; // only for the demo

function getValue() {
  var checks = document.querySelectorAll('.checks:checked');
  var myChecks = [];
  if (!checks.length) return;

  for (i = 0; i < checks.length; i++) {
    myChecks.push(checks[i].value);
  }
  //var myArray = !!localStorage.getItem('str') ? JSON.parse(localStorage.getItem('str')) : [];
  
  myArray.push(myChecks.join(' '));
  
  //localStorage.setItem('str', JSON.stringify(myArray));
  console.log('str', JSON.stringify(myArray));

}
&#13;
<div class="container">
  <input type="checkbox" class="checks" value="A"> A<br>
  <input type="checkbox" class="checks" value="B"> B<br>
  <input type="checkbox" class="checks" value="C"> C<br>
  <br><br>
  <a href="#" onclick="getValue();return false;">Get Value</a>
</div>
&#13;
&#13;
&#13;