[英]How to Add/Remove localStorage when checkbox is check/uncheck with jquery?
[英]How to check/uncheck checkbox based on localStorage state
I'm trying to persist checkbox state in a HTML (Flask/Jinja2) template using just html and CSS, but I've running into strange behavior where even though localStorage saves the state correctly, state is always set as true on load. 我查了很多答案,已經卡了幾個小時,我不明白它不起作用:
HTML:
<input id="returnHeatmapsHtmlCheckbox"
type="checkbox" name="returnHeatmapsHtml" onclick="saveCheckboxState(this)" />
JS:
<script type="text/javascript">
window.onload = onPageLoad();
function onPageLoad (){
document.getElementById("returnHeatmapsHtmlCheckbox").checked = localStorage.getItem("returnHeatmapsHtmlCheckbox");
}
// <!-- Persist checkboxes -->
function saveCheckboxState(e){
var id = e.id
var val = e.checked
console.log("Saved value ID: " + id + ","+ val)
localStorage.setItem(id,val)
console.log("Loaded value ID: " + localStorage.getItem(id,val))
console.log(getSavedCheckboxState("returnHeatmapsHtmlCheckbox"))
}
function getSavedCheckboxState(v){
const default_dict = {
"returnHeatmapsHtmlCheckbox": false
};
if (!localStorage.getItem(v)) {
return default_dict[v];// return false by default.
};
return localStorage.getItem(v);
}
</script>
任何幫助將不勝感激,謝謝!
我查看了您的代碼並冒昧地重構了一些摘錄,我試圖使其盡可能與您所做的相似,您可以在下面看到結果。
HTML:
<input id="myCheckbox" type="checkbox" name="myCheckbox" />
JS:
// get the checkbox element
const myCheckbox = document.querySelector('#myCheckbox')
// responsible for setting a value in localStorage
// following the "checked" state
const setStorageState = (e) => {
const { id, checked } = e.target
localStorage.setItem(id, checked)
}
// responsible for searching and converting to Boolean
// the value set in localStorage
const getStorageState = (storageName) => {
return localStorage.getItem(storageName) === 'true'
}
// responsible for changing the state of your checkbox
const setCheckboxStateOnLoad = () => {
myCheckbox.checked = getStorageState('myCheckbox')
}
// calls the function "setStorageState" every time
// the user clicks on his checkbox
myCheckbox.addEventListener('click', setStorageState)
// calls the "setCheckboxStateOnLoad" function
// after the DOM content is loaded
document.addEventListener('DOMContentLoaded', setCheckboxStateOnLoad)
希望它有幫助,對糟糕的英語感到抱歉:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.