使用LocalStorage记住复选框的状态和textarea的值

时间:2015-09-24 06:08:02

标签: javascript jquery

在下面的演示片段中,我通过选中一个框来添加以下库(normalize,jquery,angularjs)。

我要做的是将检查状态保存在LocalStorage中,这样当我刷新页面时,我检查的库将保持检查状态。

有关如何做到这一点的任何想法? (最好采用DRY

的方式

$(document).ready(function() {
  // Save Checked Libraries for LocalStorage
  if ( localStorage.getItem("checkedLibraries")) {
    $("div").html(localStorage.getItem("checkedLibraries")); 
  }
  $(".check").on("change", function() {
    var textarea = $('.full-library-code');
    var value = $(this).nextAll('input:first').val() + '\n';

    if ( $(this).prop('checked') == true ) {
      textarea.val( textarea.val() + value );
    } else {
      textarea.val( textarea.val().replace( value, "") );
    }
    localStorage.setItem("checkedLibraries", $("div").html());
  });
});
/* only for demo readability */
textarea { width: 500px; height: 200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="checkbox" class="check" id="norm" /> <label for="norm">Normalize</label>
  <input type="text" class="hide" value='&lt;link rel="stylesheet" href="http://necolas.github.io/normalize.css/3.0.1/normalize.css" /&gt;' /><br />
  <input type="checkbox" class="check" id="jquery" /> <label for="jquery">JQuery</label>
  <input type="text" class="hide" value='&lt;script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;' /><br />
  <input type="checkbox" class="check" id="ang" /> <label for="ang">Angular JS</label>
  <input type="text" class="hide" value='&lt;link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" /&gt;' /><br />
  <textarea class="full-library-code" placeholder="full library's code"></textarea>
</div>

3 个答案:

答案 0 :(得分:2)

试试这个:

  

您还需要在 localstorage 中存储复选框

 $(document).ready(function() {
   var textarea = $('.full-library-code');
   // Save Checked Libraries for LocalStorage
   if (localStorage.getItem("checkedLibraries")) {
     textarea.val(localStorage.getItem("checkedLibraries"));

     var lsStored = JSON.parse(localStorage.getItem('checkedInputs')) || [];
     for (var j = 0, jLen = lsStored.length; j < jLen; j++) {
       $('#' + lsStored[j]).prop('checked', true);
     }
   }
   $(".check").on("change", function() {


     var value = $(this).nextAll('input:first').val() + '\n';

     if ($(this).prop('checked') == true) {
       textarea.val(textarea.val() + value);
     } else {
       textarea.val(textarea.val().replace(value, ""));
     }
     var checked = $('[type=checkbox].check:checked');
     var lsChecked = [];
     for (var i = 0, iLen = checked.length; i < iLen; i++) {
       lsChecked.push($(checked[i]).attr('id'))
     }
     localStorage.setItem("checkedLibraries", textarea.val());
     localStorage.setItem("checkedInputs", JSON.stringify(lsChecked));
   });
 });
textarea {
  width: 500px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="check" id="norm" />
<label for="norm">Normalize</label>
<input type="text" class="hide" value='&lt;link rel="stylesheet" href="http://necolas.github.io/normalize.css/3.0.1/normalize.css" /&gt;' />
<br/>
<input type="checkbox" class="check" id="jquery" />
<label for="jquery">JQuery</label>
<input type="text" class="hide" value='&lt;script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;' />
<br/>
<input type="checkbox" class="check" id="ang" />
<label for="ang">Angular JS</label>
<input type="text" class="hide" value='&lt;link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" /&gt;' />
<br/>
<textarea class="full-library-code" placeholder="full library's code"></textarea>

答案 1 :(得分:1)

HTML:为每个输入元素提供name属性

<input type="checkbox" class="check" id="norm" name="norm" />
  <label for="norm">Normalize</label>
  <input type="text" class="hide" value='&lt;link rel="stylesheet" href="http://necolas.github.io/normalize.css/3.0.1/normalize.css" /&gt;' />
  <br />
  <input type="checkbox" class="check" id="jquery" name="jquery" />
  <label for="jquery">JQuery</label>
  <input type="text" class="hide" value='&lt;script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;' />
  <br />
  <input type="checkbox" class="check" id="ang" name="ang" />
  <label for="ang">Angular JS</label>
  <input type="text" class="hide" value='&lt;link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" /&gt;' />
  <br />
  <textarea class="full-library-code" placeholder="full library's code"></textarea>

使用Javascript:

$(function() {
  $(".check").on("change", function() {
    var textarea = $('.full-library-code');
    var value = $(this).nextAll('input:first').val() + '\n';
    if ($(this).prop('checked') == true) {
      textarea.val(textarea.val() + value);
    } else {
      textarea.val(textarea.val().replace(value, ""));
    }
    var getAllCheckBoxes = $('input[type="checkbox"]');
    var allCheckBoxes = [].map.call(getAllCheckBoxes, function(checkbox) {
      return {
        name: checkbox.name,
        checked: checkbox.checked
      };
    });
    localStorage.setItem("allCheckBoxes", JSON.stringify(allCheckBoxes));
  });

  //Check if localstorage has allCheckBoxes
  if (localStorage.getItem("allCheckBoxes")) {
    var checkBoxes = JSON.parse(localStorage.getItem("allCheckBoxes"));
    var getAllCheckBoxes = $('input[type="checkbox"]');
    [].forEach.call(getAllCheckBoxes, function(checkbox) {
      checkBoxes.forEach(function(box) {
        if (box.checked && checkbox.name == box.name) {
          checkbox.checked = box.checked;
          $(checkbox).change(); //Trigger Change
        }
      });
    });
  }
});

Plunker

答案 2 :(得分:1)

这里没有更简单或有效的方法:)

Here is the JSFiddle demo

// CODE

<!DOCTYPE html>
<html>
<head>
     <script>
        var frameworks = {
            "normalize":"http://necolas.github.io/normalize.css/3.0.1/normalize.css",
            "jquery":"http://code.jquery.com/jquery-latest.min.js",
            "angular":"https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"
        };
        document.onreadystatechange = function(){
            if(document.readyState == "interactive"){
                var formChildren = document.getElementById("formbox").children;
                for(var i=0; i < formChildren.length; i++){
                    if(formChildren[i].tagName === "INPUT"){
                        var inputFrame = formChildren[i].getAttribute("data-framework");
                        if(localStorage.getItem(inputFrame) !== null){
                            formChildren[i].checked = true;
                        }
                        formChildren[i].addEventListener("change", checkFramework);
                    }
                }
            }
        }
        function checkFramework(e){
            var framework = e.target.getAttribute("data-framework");
            if(e.target.checked){
                localStorage.setItem(framework, frameworks[framework])
            }
            else{
                localStorage.removeItem(framework);
            }
        }
     </script>
</head>
<body>
</script>
    <form id="formbox">
<!--        NORMALIZE -->
        <input type="checkbox" data-framework="normalize"> 
        <label>Normalize</label> 

<!--         JQUERY -->
        <input type="checkbox" data-framework="jquery"> 
        <label>JQuery</label> 

<!--         ANGULAR         -->
        <input type="checkbox" data-framework="angular"> 
        <label>Angular JS</label> 
    </form>
</body>
</html>