Jak zapamiętać, czy pole jest zaznaczone lub odznaczone (po kliknięciu) z lokalnym przechowywaniem, a także zapisać wartość?
Oto jsfiddle:http://jsfiddle.net/nng6L/7/
Chcę więc:
Chcę ustawić wartość w lokalnym miejscu przechowywania1
jeśli pole jest zaznaczone, lub0
jeśli pole nie jest zaznaczonePo ponownym załadowaniu strony, jeśli pole zostało zaznaczone, pozostaje sprawdzone, po pobraniu wartości z lokalnego magazynuChcę móc wyświetlać a1
lub a0
zwykłym tekstem, po pobraniu wyżej wymienionej wartości z lokalnego magazynu.Oto mój kod, ale nie działa (po ponownym załadowaniu strony pole nie jest zaznaczone; inull
jest zwracane zamiast a1
lub a0
):
script.js
// here is to set item in localstorage when you click the check box.
vvvvvvv = document.getElementById('xxxx');
vvvvvvv.onclick = function() {
if(document.getElementById('xxxx').checked=true) {
localStorage.setItem('yyyyyyy', "1");
} else {
localStorage.setItem('yyyyyyy', "0");
}
}
// here is to fetch the item stored in local storage, and use that value
// to check or uncheck the box based on localstorage value.
zzzzzzz = localStorage.getItem('yyyyyyy');
if (zzzzzzz === null) {
localStorage.setItem('yyyyyyy', "0");
document.getElementById("xxxx").checked=false;
}
else {
if (zzzzzzz === "1") {
document.getElementById("xxxx").checked=true;
} else if (zzzzzzz === "0") {
document.getElementById("xxxx").checked=false;
}
}
output.js
// here is to output the value to the web page so we can know
// what value is stored in localstorage.
wwwwwwww = localStorage.getItem('yyyyyyy');
document.write(wwwwwwww);
page.html
<!-- here is the check box for which the scripts above are based from -->
<input type="checkbox" id="xxxx">Do you like summer?
<br><br>
<!-- here is where it will display the value from localstorage -->
<script src="output.js">