【问题标题】:Store Checkbox 'Checked' with localstorage for multiple items使用本地存储存储多个项目的复选框“已选中”
【发布时间】:2014-08-19 03:34:11
【问题描述】:

我想将我的复选框保存到本地存储,但是我使用的这段代码对于多个复选框来说太麻烦了....有没有更好的方法来做到这一点?

setStatus = document.getElementById('LineOp');
setStatus.onclick = function() {
    if(document.getElementById('LineOp').checked) {
        localStorage.setItem('LineOp', "true");
    } else {
        localStorage.setItem('LineOp', "false");
    }
}


getStstus = localStorage.getItem('LineOp');
if (getStstus == "true") {
    alert("Welcome Back");
    document.getElementById("LineOp").checked = true;
} else {
    console.log("News");
}

【问题讨论】:

    标签: javascript jquery checkbox input local-storage


    【解决方案1】:

    既然你用的是jQuery,试试:

    var getStstus = localStorage.getItem('LineOp');
    
    if (getStstus === "true")
        $("#LineOp").prop("checked", true);
    
    $("#LineOp").click(function(){
        localStorage.setItem('LineOp', $(this).prop("checked"));
    });
    

    jsFiddle

    【讨论】:

      【解决方案2】:

      这是一种可以放置任意数量复选框的方法,只需添加带有唯一标识符的 store 属性以用于本地存储。 JSFiddle

      var boxes = document.querySelectorAll("input[type='checkbox']");
      
      for (var i = 0; i < boxes.length; i++) {
          var box = boxes[i];
          if (box.hasAttribute("store")) {
              setupBox(box);
          }
      }
      
      function setupBox(box) {
          var storageId = box.getAttribute("store");
          var oldVal    = localStorage.getItem(storageId);
          box.checked = oldVal === "true" ? true : false;
      
          box.addEventListener("change", function() {
              localStorage.setItem(storageId, this.checked); 
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-19
        • 1970-01-01
        • 2015-05-24
        • 2018-12-18
        • 2017-07-20
        • 1970-01-01
        • 2014-03-31
        • 2012-07-02
        相关资源
        最近更新 更多