第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

富國滬深 2022-06-09 10:30:31
假設(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)的更好方法嗎?提前一百萬謝謝??!
查看完整描述

1 回答

?
幕布斯6054654

TA貢獻(xiàn)1876條經(jīng)驗 獲得超7個贊

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

有關(guān) Javascript 序列化的更多指導(dǎo),請參閱此問題。

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


查看完整回答
反對 回復(fù) 2022-06-09
  • 1 回答
  • 0 關(guān)注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號