2015-09-24 2 views
0

В следующем демонстрационном фрагменте я добавляю следующие библиотеки (normalize, jquery, angularjs) через html, установив флажок.Использовать LocalStorage для запоминания состояния и значения поля флажка

То, что я пытаюсь сделать, это сохранить проверенное состояние в 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>

+0

Что означает aany этого? И почему вы делаете вещи с '$ (" div ")', если у вас даже нет div? И почему вы не ** создаете MCVE? – Amit

+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

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

1

Не получить любой простой или эффективный то это право здесь :)

Here is the JSFiddle demo

// КОД

<!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> 
Смежные вопросы