我是一個初學者程式員,我正在做我的第一個小專案。我決定做一個筆記應用程式。它基本上完成了,除了我想要一個按鈕來洗掉所有已完成的任務并且我遇到了問題。基本上,它適用于 localStorage,我將任務名稱存盤為鍵,其值為 0(未完成)或 1(已完成)。在最后一個函式中,我想洗掉 localStorage 值為 1 的所有任務。這是我的代碼。運行它后,我在洗掉所有 li 元素時遇到問題。有些會被洗掉,有些不會。在控制臺中,我看到兩個未宣告 tableChild 的錯誤。這似乎很奇怪。
document.querySelector(".btn-delete-completed").addEventListener("click", function () {
let children = listOfTasks.children; /*takes an ul element (listOfTasks) and selects its child elements*/
let arrayLenght = children.length; /*variable to see the lenght of the created arrray*/
let tableChild = 0; /*creates a variable that will be redeclared in the loop dynamically*/
for (let i = 0; i < arrayLenght; i ) { /*for loop that takes a stative arrayLenght instead of dynamic one(since we will be deleting elements)*/
tableChild = children[i]; /*redeclares a tableChild variable to a single li with the text that is a key to localStorage*/
if (localStorage.getItem(tableChild.textContent) == 1) {/*Checks for the value in localStorage, getItem() uses the key that is text of the selected element*/
tableChild.remove();/*removes the element from html*/
localStorage.removeItem(tableChild.textContent); /*removes element from localStorage*/
}
}
});
這里是。我希望檔案足夠好。正如我所說,我只是一個初學者,我是第一次在這里發帖。如果您有任何問題,我很樂意在評論中回答!如果我在這篇文章中搞砸了,再次抱歉。
提前致謝!
uj5u.com熱心網友回復:
當您從陣列中洗掉元素時,其長度會發生變化。這不在您的代碼中。
我發現在這種情況下最容易向后迭代:
for (let i = children.length - 1; i >= 0; i--){
//...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/424740.html
標籤:javascript for循环 本地存储
