使用LocalStorage保存复选框值



我有一个由复选框状态切换的show/hidediv,尽管它工作正常,但我想让localstorage保存复选框状态,但是我不知道如何实现代码的本地存储部分以及将其放置的位置。感激地收到的任何帮助。

  $(document).ready(function() {
    $('#checkbox1').change(function() {
        $('#div1').toggle();
    });
});
<input type="checkbox" id="checkbox1" value="1" />
<div id="div1">Text to be toggled</div>

尝试一下:http://jsfiddle.net/squey/4/

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

我必须在本地存储中保存复选框的值,也许这将指导您将数据存储在本地存储中。我做了一个复选框和一个按钮。单击"保存"按钮时,称为函数,该函数获取复选框的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;

检查以下内容:

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")
    }
  });
});

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)
  });
});

最新更新