假設(shè)我有一堂課:Class Comment { constructor(user, comment) { this.username = document.createElement("span"); this.comment = document.createElement("p"); this.body = document.querySelector("body"); } createComment() { this.username.textContent = user; this.commet.textContent = comment; body.appendChild(this.username); body.appendChild(this.comment); }}每次用戶在頁面上輸入用戶名和評論并點擊提交按鈕時,它都會創(chuàng)建一個新的類實例(新評論!):const submitButton = document.querySelector("#submitButton");submitButton.addEventListener("click", () => { let addComment = new Comment(userInput.value, commentInput.value);}我想將這些實例中的每一個存儲在 localStorage 中(按順序):exisitingComments = []localStorage.setItem("existingComments", JSON.stringify(existingComments));存儲分配給實例的變量 (addComment) 會導(dǎo)致方法 createComment 在加載時未定義:window.onload = function() { existingComments = JSON.parse(localStorage.existingComments); let i = existingComments.length - 1; for (; i >= 0; i--) { existingComments[i].createCommet() }}-> TypeError: existingComments[i].createComment is not a function我無法存儲用戶名和評論并創(chuàng)建新的類實例,因為用戶名和評論不應(yīng)該是唯一的,如果用戶想刪除評論我無法知道它在 localStorage 中的位置(如果讓我們說有多個相同的評論)。起作用的一件事是每次單擊提交按鈕時,調(diào)用一個函數(shù)來循環(huán)整個評論部分:const commentSection = document.querySelector("#commentSection").children;for (x = 0; x < commentSection.length - 1; x++) { commentSection[x].setAttribute("id", `comment#{x}`);}這些 id 對應(yīng)于 localStorage 中評論的位置。任何人都知道可以實現(xiàn)的更好方法嗎?提前一百萬謝謝??!
Javascript:如何在 LocalStorage 中存儲類的實例?
富國滬深
2022-06-09 10:30:31