亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript:如何在 LocalStorage 中存儲類的實例?

Javascript:如何在 LocalStorage 中存儲類的實例?

富國滬深 2022-06-09 10:30:31
假設我有一堂課: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);    }}每次用戶在頁面上輸入用戶名和評論并點擊提交按鈕時,它都會創建一個新的類實例(新評論!):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) 會導致方法 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我無法存儲用戶名和評論并創建新的類實例,因為用戶名和評論不應該是唯一的,如果用戶想刪除評論我無法知道它在 localStorage 中的位置(如果讓我們說有多個相同的評論)。起作用的一件事是每次單擊提交按鈕時,調用一個函數來循環整個評論部分:const commentSection = document.querySelector("#commentSection").children;for (x = 0; x < commentSection.length - 1; x++) {    commentSection[x].setAttribute("id", `comment#{x}`);}這些 id 對應于 localStorage 中評論的位置。任何人都知道可以實現的更好方法嗎?提前一百萬謝謝??!
查看完整描述

1 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

這里的核心問題是本地存儲僅存儲字符串(文檔)并且您使用的是 JSON 編碼。JSON 不支持類或 DOM 元素。您需要引入某種序列化來表示您的類并稍后對其進行補充。

有關 Javascript 序列化的更多指導,請參閱此問題。

該問題中沒有評論 DOM 問題,但是如果您的反序列化機制創建了Comment類的新實例,它應該具有創建新 DOM 元素的副作用。


查看完整回答
反對 回復 2022-06-09
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號