【问题标题】:Keep the checkbox inputs checked using localStorage使用 localStorage 检查复选框输入
【发布时间】:2018-08-25 22:51:01
【问题描述】:

我目前正在学习localStorage,并尝试使用checkbox、localStorage实现一些基本功能。基本上,我要实现的目的是每当检查复选框时,我希望在重新加载后继续检查它们。

查看:

 <div>
    <label><input type="checkbox"value="<%=obj.id%>" name="selected" class="select_class"></label>
 </div>

JS

  $("#save_button").click(function(){
    var selecteditems = [];

      if (!$("input[name='selected']:checked").is(":checked")) {
          localStorage.removeItem('chx');
         //if checkboxs are not checked, remove the setItem
        }
      else{
        $("input[name='selected']:checked").each(function(){
        var checked = $(this).val();
        if(checked){
          selecteditems.push(checked);

        localStorage.setItem('chx', JSON.stringify(selecteditems));
        var localcheckdata =JSON.parse(localStorage.getItem('chx'));  
        }

        $.each($("input[name='selected']"), function(){
         localcheckdata.push($(this).val());
       });

非常感谢您的帮助,如果您不介意,请告诉我问题所在?

【问题讨论】:

    标签: javascript local-storage


    【解决方案1】:

    您需要在保存时存储值,获取 dom 中每个复选框元素的 ID。

    然后一旦页面加载回来,你必须重申存储在本地存储中的值,然后更新 dom

    你的代码有一些未知的变量,因此下面这个例子:

    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
        $checkboxes = $("#checkbox-container :checkbox");
    
    // on save button clicked
    $("#save_button").click(function(){
      $checkboxes.each(function(){
        checkboxValues[this.id] = this.checked;
      });
    
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    
    });
    
    
    // On page load
    $.each(checkboxValues, function(key, value) {
      $("#" + key).prop('checked', value);
    });
    <div id="checkbox-container">
      <div>
        <label for="option1">Option 1</label>
        <input type="checkbox" id="option1">
      </div>
      <div>
        <label for="option2">Option 2</label>
        <input type="checkbox" id="option2">
      </div>
      <div>
        <label for="option3">Option 3</label>
        <input type="checkbox" id="option3">
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      相关资源
      最近更新 更多