gpt4 book ai didi

javascript - 如何使用 innerHTML 将从本地存储检索到的对象传递到 DOM?

转载 作者:行者123 更新时间:2023-12-04 09:25:50 30 4
gpt4 key购买 nike

我正在尝试使用 innerHTML 将保存在 localStorage 中的所有数据传递到 DOM 中。然而,showCollections()单击提交按钮或重新加载页面后,不会返回本地存储中检索到的所有数据。它只返回 collectionObj 中的最后一项大批。
这是我迄今为止尝试过的:

//get form values 
// create an object of the form values
//create an empty array
//append object of the form values to the empty array
//display array object values

showCollection();

var getButton = document.getElementById('clickIt');
var collectionTitle = document.getElementById("title");
var collectionDescription = document.getElementById('describe')


getButton.addEventListener('click', function(e){
e.preventDefault()
var collections = {
title: collectionTitle.value,
description: collectionDescription.value
}

let webCollections = localStorage.getItem('collectx');
if(webCollections == null){
var collectionObj = []
alert('storage is empty')
}
else{
collectionObj = JSON.parse(webCollections);
}
collectionObj.push(collections);
localStorage.setItem("collectx", JSON.stringify(collectionObj));
showCollection()
});


function showCollection(){
let webCollections = localStorage.getItem('collectx')
if(webCollections == null){
var collectionObj = []
alert('storage is empty')
}
else{
collectionObj = JSON.parse(webCollections);
}
let html= ''
var demos = document.getElementById('demo');
collectionObj.forEach(function(item, index){
html = `<p> this is a description ${item.title} and description: ${item.description} </p>`
})
demos.innerHTML = html


}
    
<form id="forms">
<input id="title" type="text" placeholder="Collection name">
<br>
<br>
<input id="describe" type="text" placeholder="Description">
<button id="clickIt"> Submit </button>
</form>

<div id="demo">

</div>

最佳答案

需要加一个“+”号,

html += `<p> this is a description ${item.title} and description: ${item.description} </p>

这会将所有内容呈现到网页上。

关于javascript - 如何使用 innerHTML 将从本地存储检索到的对象传递到 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63013013/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com