簡體   English   中英

刷新頁面后,如何確保從 localStorage 顯示正確的數據?

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

我正在整理一個簡單的待辦事項應用程序,我希望在根據添加到 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. 我錯過了什么?

 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的是 Boolean 屬性。 僅在元素中存在它就意味着應該對其進行檢查。 當您檢查localStorage中的值並發現雖然它正確存儲false時,您將其設置為什么值並沒有區別,但該復選框總是返回選中狀態。

有關上面的更多詳細信息,請參閱此內容。

因此,在您的getItemsFromLocalStorage() function 中,您需要首先檢查該屬性是否最后設置為true ,如果是這種情況,則僅設置checked的屬性。 如果不是,則根本不要設置該屬性。

// 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);
}

雖然下面的代碼是正確的,但由於沙盒,它不會在 Stack Overflow 上運行。 但是,您可以在這里進行測試

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM