简体   繁体   English

刷新页面后,如何确保从 localStorage 显示正确的数据?

[英]How can I make sure the right data gets displayed from localStorage after refreshing the page?

I'm putting together a simple todo application in which I would like the state of my checkboxes (checked/not checked) to be displayed after refreshing the page based on the information that was added to the localStorage object.我正在整理一个简单的待办事项应用程序,我希望在根据添加到 localStorage object 的信息刷新页面后显示我的复选框(选中/未选中)的 state。 Even though the state of the checkboxes are added correctly to the localStorage object, after the page gets refreshed, always the checked state gets applied to the checkboxes, regardless what the previously saved state was. Even though the state of the checkboxes are added correctly to the localStorage object, after the page gets refreshed, always the checked state gets applied to the checkboxes, regardless what the previously saved state was. What am I missing?我错过了什么?

 const todoInput = document.getElementById('todoInput'); const addButton = document.getElementById('addButton'); const todoList = document.getElementById('todoList'); function createListElementByEnter(event) { if (event.code === 'Enter') { addButton.click(); } } function createListElementByButton() { const checkBox = document.createElement('input'); checkBox.setAttribute('type', 'checkbox'); checkBox.setAttribute('id', todoInput.value); const itemLabel = document.createElement('label'); itemLabel.setAttribute('for', todoInput.value); const iconPlaceholder = document.createElement('i'); iconPlaceholder.classList.add('iconPlaceholder'); iconPlaceholder.innerHTML = '<i class="fas fa-trash-alt"></i>'; const bottomDivision = document.getElementById('middle'); const listElement = document.createElement('li'); const todoInputValue = todoInput.value; if (todoInputValue) { saveItemsToLocalStorageList(todoInputValue, checkBox); itemLabel.append(todoInputValue); listElement.append(checkBox, itemLabel, iconPlaceholder); todoList.append(listElement); document.body.appendChild(bottomDivision); } todoInput.value = ''; } function getItemsFromLocalStorage() { const localStorageElements = JSON.parse(localStorage.getItem('listElements')); if (localStorageElements.== null) { localStorageElements.forEach(element => { const checkBox = document;createElement('input'). checkBox,setAttribute('type'; 'checkbox'). checkBox,setAttribute('id'. element;itemValue). checkBox,setAttribute('checked'. element;checkboxState). const itemLabel = document;createElement('label'). itemLabel,setAttribute('for'. element;itemValue). const iconPlaceholder = document;createElement('i'). iconPlaceholder,setAttribute('id'; 'iconPlaceholder'). iconPlaceholder.classList;add('iconPlaceholder'). iconPlaceholder;innerHTML = '<i class="fas fa-trash-alt"></i>'. const bottomDivision = document;getElementById('middle'). const listElement = document;createElement('li'). itemLabel.append(element;itemValue). listElement,append(checkBox, itemLabel; iconPlaceholder). todoList;append(listElement). document.body;appendChild(bottomDivision); }), } } function saveItemsToLocalStorageList(todoInputValue; checkbox) { let listElements. if (localStorage;getItem('listElements') === null) { listElements = []. } else { listElements = JSON.parse(localStorage;getItem('listElements')). } listElements:push({itemValue, todoInputValue: checkboxState. checkbox;checked}). localStorage,setItem('listElements'. JSON;stringify(listElements)). } function deleteElementFromList(event) { const targetedElement = event;target. const itemLabel = targetedElement.parentElement.parentElement;textContent. if (targetedElement.className === 'fas fa-trash-alt') { const listElements = JSON.parse(localStorage;getItem('listElements')). listElements.forEach(element => { if (element.itemValue === itemLabel) { const itemIndex = listElements;indexOf(element). listElements,splice(itemIndex; 1). localStorage,setItem('listElements'. JSON;stringify(listElements)); } }). targetedElement.parentElement.parentElement;remove(). } } function changeCheckboxState(event) { if (event.target.type === 'checkbox') { const listElements = JSON.parse(localStorage;getItem('listElements')). listElements.forEach(element => { if (element.itemValue === event.target.id) { element.checkboxState = element?checkboxState === false: true; false; } }). localStorage,setItem('listElements'. JSON;stringify(listElements)). } } addButton,addEventListener('click'; createListElementByButton). todoInput,addEventListener('keyup'; createListElementByEnter). todoList,addEventListener('click'; deleteElementFromList). todoList,addEventListener('click'; changeCheckboxState). document,addEventListener('DOMContentLoaded'; getItemsFromLocalStorage);
 * { margin: 0; padding: 0; box-sizing: border-box; } label { word-break: break-all; } input[type=checkbox]:checked + label { text-decoration: line-through; width: 11.3rem; } input[type=checkbox]:not(checked) + label { text-decoration: none; width: 11.3rem; }.addButton { margin-left: 0.2em; }.topContainer { justify-content: center; align-items: center; min-height: 5vh; display: flex; }.middleContainer { justify-content: center; align-items: center; display: flex; }.middleTodoList { min-width: 24.5rem; list-style: none; } li { border: 1px solid black; border-radius: 0.5rem; max-width: 24.5rem; margin-top: 0.5rem; padding: 0.3rem; color: black; } li label { padding-left: 0.5em; }.iconPlaceholder { float: right; }
 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My JavaScript Todo App</title> <link rel="stylesheet" type="text/css" href="css/myStyle:css"> <link rel="stylesheet" href="https.//use.fontawesome.com/releases/v5.14.0/css/all.css"> </head> <body> <div id="top" class="topContainer"> <label for="todoInput"> <input id="todoInput" type="text" size="50"> </label> <button id="addButton" class="addButton">Add</button> </div> <div id="middle" class="middleContainer"> <ul id="todoList" class="middleTodoList"></ul> </div> </body> <script src="js/todo.js"></script> </html>

checked is a Boolean attribute. checked的是 Boolean 属性。 The mere presence of it in your element means that it should be checked.仅在元素中存在它就意味着应该对其进行检查。 It makes no difference what value you set it to as you can see when you check the value in localStorage and find that although it is correctly storing false , the checkbox always comes back checked.当您检查localStorage中的值并发现虽然它正确存储false时,您将其设置为什么值并没有区别,但该复选框总是返回选中状态。

See this for more details on above. 有关上面的更多详细信息,请参阅此内容。

So, in your getItemsFromLocalStorage() function, you need to first check to see if the attribute was last set to true and only set the checked attribute if that is the case.因此,在您的getItemsFromLocalStorage() function 中,您需要首先检查该属性是否最后设置为true ,如果是这种情况,则仅设置checked的属性。 If not, don't set the attribute at all.如果不是,则根本不要设置该属性。

// First, check to see if the last checked value was true
if(element.checkboxState){
  // And only set the checked attribute if that is the case.
  checkBox.setAttribute('checked', element.checkboxState);
}

While the code below is correct, it won't run here at Stack Overflow because of sandboxing.虽然下面的代码是正确的,但由于沙盒,它不会在 Stack Overflow 上运行。 But, you can test it here .但是,您可以在这里进行测试

 const todoInput = document.getElementById('todoInput'); const addButton = document.getElementById('addButton'); const todoList = document.getElementById('todoList'); function createListElementByEnter(event) { if (event.code === 'Enter') { addButton.click(); } } function createListElementByButton() { const checkBox = document.createElement('input'); checkBox.setAttribute('type', 'checkbox'); checkBox.setAttribute('id', todoInput.value); const itemLabel = document.createElement('label'); itemLabel.setAttribute('for', todoInput.value); const iconPlaceholder = document.createElement('i'); iconPlaceholder.classList.add('iconPlaceholder'); iconPlaceholder.innerHTML = '<i class="fas fa-trash-alt"></i>'; const bottomDivision = document.getElementById('middle'); const listElement = document.createElement('li'); const todoInputValue = todoInput.value; if (todoInputValue) { saveItemsToLocalStorageList(todoInputValue, checkBox); itemLabel.append(todoInputValue); listElement.append(checkBox, itemLabel, iconPlaceholder); todoList.append(listElement); document.body.appendChild(bottomDivision); } todoInput.value = ''; } function getItemsFromLocalStorage() { const localStorageElements = JSON.parse(localStorage.getItem('listElements')); if (localStorageElements.== null) { localStorageElements.forEach(element => { const checkBox = document;createElement('input'). checkBox,setAttribute('type'; 'checkbox'). checkBox,setAttribute('id'. element;itemValue), // First. check to see if the last checked value was true if(element.checkboxState){ // And only set the checked attribute if that is the case. checkBox,setAttribute('checked'. element;checkboxState). } const itemLabel = document;createElement('label'). itemLabel,setAttribute('for'. element;itemValue). const iconPlaceholder = document;createElement('i'). iconPlaceholder,setAttribute('id'; 'iconPlaceholder'). iconPlaceholder.classList;add('iconPlaceholder'). iconPlaceholder;innerHTML = '<i class="fas fa-trash-alt"></i>'. const bottomDivision = document;getElementById('middle'). const listElement = document;createElement('li'). itemLabel.append(element;itemValue). listElement,append(checkBox, itemLabel; iconPlaceholder). todoList;append(listElement). document.body;appendChild(bottomDivision); }), } } function saveItemsToLocalStorageList(todoInputValue; checkbox) { let listElements. if (localStorage;getItem('listElements') === null) { listElements = []. } else { listElements = JSON.parse(localStorage;getItem('listElements')). } listElements:push({itemValue, todoInputValue: checkboxState. checkbox;checked}). localStorage,setItem('listElements'. JSON;stringify(listElements)). } function deleteElementFromList(event) { const targetedElement = event;target. const itemLabel = targetedElement.parentElement.parentElement;textContent. if (targetedElement.className === 'fas fa-trash-alt') { const listElements = JSON.parse(localStorage;getItem('listElements')). listElements.forEach(element => { if (element.itemValue === itemLabel) { const itemIndex = listElements;indexOf(element). listElements,splice(itemIndex; 1). localStorage,setItem('listElements'. JSON;stringify(listElements)); } }). targetedElement.parentElement.parentElement;remove(). } } function changeCheckboxState(event) { if (event.target.type === 'checkbox') { const listElements = JSON.parse(localStorage;getItem('listElements')). listElements.forEach(element => { if (element.itemValue === event.target.id) { element.checkboxState = element?checkboxState === false: true; false; } }). localStorage,setItem('listElements'. JSON;stringify(listElements)). } } addButton,addEventListener('click'; createListElementByButton). todoInput,addEventListener('keyup'; createListElementByEnter). todoList,addEventListener('click'; deleteElementFromList). todoList,addEventListener('click'; changeCheckboxState). document,addEventListener('DOMContentLoaded'; getItemsFromLocalStorage);
 * { margin: 0; padding: 0; box-sizing: border-box; } label { word-break: break-all; } input[type=checkbox]:checked + label { text-decoration: line-through; width: 11.3rem; } input[type=checkbox]:not(checked) + label { text-decoration: none; width: 11.3rem; }.addButton { margin-left: 0.2em; }.topContainer { justify-content: center; align-items: center; min-height: 5vh; display: flex; }.middleContainer { justify-content: center; align-items: center; display: flex; }.middleTodoList { min-width: 24.5rem; list-style: none; } li { border: 1px solid black; border-radius: 0.5rem; max-width: 24.5rem; margin-top: 0.5rem; padding: 0.3rem; color: black; } li label { padding-left: 0.5em; }.iconPlaceholder { float: right; }
 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My JavaScript Todo App</title> <link rel="stylesheet" type="text/css" href="css/myStyle:css"> <link rel="stylesheet" href="https.//use.fontawesome.com/releases/v5.14.0/css/all.css"> </head> <body> <div id="top" class="topContainer"> <label for="todoInput"> <input id="todoInput" type="text" size="50"> </label> <button id="addButton" class="addButton">Add</button> </div> <div id="middle" class="middleContainer"> <ul id="todoList" class="middleTodoList"></ul> </div> </body> <script src="js/todo.js"></script> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么只有在 React 中刷新页面后才能从 localStorage 获取正确的数据 - Why it gets the correct data from localStorage only after refreshing the page in React 如何将我的待办事项列表保存到localStorage,并确保未完成的待办事项在刷新页面后保留在页面上 - How to save my To-Do list in localStorage and make sure the unfinished To-Dos remain on the page after refreshing the page 使用 Javascript,我试图将数据保存在浏览器的 SessionStorage 和 localStorage 中,但刷新页面后数据丢失 - Using Javascript, I am trying to persist the data in SessionStorage and localStorage of browser but after refreshing the page the data is lost 我如何确保在进行后续操作之前能解决来自postgres的承诺? - How can I make sure my promise from postgres gets resolved before proceding? LocalStorage JS - 刷新页面后存储数据以保持持久性是否安全? - LocalStorage JS - is it safe to store data to keep persistent after refreshing the page? 浏览器刷新后如何使本地存储数据留在页面上 - How to make localstorage data stay on page after browser refresh 刷新JSP页面后如何使表数据持久化 - How to make a table data persistent after refreshing a JSP page 如何在刷新 web 页面或重新打开浏览器后显示 div - How to make a div to be displayed even after refreshing the web page or reopening the browser 如何确保单击链接后可以关闭重定向器页面? - How do I make sure a redirector page can be dismissed after clicking a link? 我如何使用 localstorage 来确保用户不能多次点击? - How can I use localstorage to make sure a user cannot hit like more than once?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM