【问题标题】:Use localStorage to save a checkbox value使用 localStorage 保存复选框值
【发布时间】:2017-04-17 07:10:59
【问题描述】:

我有一个由复选框状态切换的显示/隐藏 div,虽然它工作正常我想让 localStorage 保存复选框状态,但我不知道如何实现代码的本地存储部分和在哪里放置它。感谢您提供任何帮助。

  $(document).ready(function() {
    $('#checkbox1').change(function() {
        $('#div1').toggle();
    });
});

<input type="checkbox" id="checkbox1" value="1" />
<div id="div1">Text to be toggled</div>

【问题讨论】:

    标签: javascript html checkbox local-storage


    【解决方案1】:

    我必须将复选框的值保存在本地存储中,也许这会指导您将数据存储在本地存储中。 我做了一个复选框和一个按钮。单击“保存”按钮时,将调用一个函数,该函数获取复选框的 id 并将其存储在 localStorage.setItem() 中。

       <input type="checkbox" id="cb1">checkbox</input>
       <button type="button" onClick="save()">save</button>
       function save() {    
       var checkbox = document.getElementById("cb1");
       localStorage.setItem("cb1", checkbox.checked);   
       }
    
      //for loading
       var checked = JSON.parse(localStorage.getItem("cb1"));
      document.getElementById("cb1").checked = checked;
    

    【讨论】:

      【解决方案2】:

      试试这个:http://jsfiddle.net/sQuEy/4/

      checkboxes[i].checked = localStorage.getItem(checkboxes[i].value) === 'true' ? true:false;
      

      【讨论】:

        【解决方案3】:

        jsfiddle

        jQuery(function($) { // Shorter document ready & namespace safer
        
          // initiate the state
          var checked = localStorage.getItem('checkbox1')
          if (checked) {
            $('#div1').hide()
            $('#checkbox1').prop('checked', true)
          }
        
          // Toggle the visibility
          $('#checkbox1').change(function() {
            $('#div1').toggle();
            this.checked 
              ? localStorage.setItem(this.id, true)
              : localStorage.removeItem(this.id)
          });
        });
        

        【讨论】:

          【解决方案4】:

          检查一下:

          LocalStorage

          $(document).ready(function() {
            $('#checkbox1').change(function() {
              $('#div1').toggle();
              if (typeof(Storage) !== "undefined") {
                localStorage.setItem("CheckboxValue", $('#checkbox1').is(":checked"));
              } else {
                console.log("No Support for localstorage")
              }
            });
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-07-31
            • 2017-05-05
            • 1970-01-01
            • 2012-10-01
            • 1970-01-01
            • 2015-07-25
            • 2020-02-03
            • 1970-01-01
            相关资源
            最近更新 更多