【发布时间】:2020-11-20 21:53:59
【问题描述】:
我正在开发一个书签“收藏家”应用程序,该应用程序允许用户将网站网址保存为集合。我在本地存储中创建了一个数组 collectX 来保存每个集合。但是,我正在尝试编辑和更新在另一个 HTML 页面上创建的每个集合。
我该怎么做?
这是我迄今为止尝试过的:
//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,
collectedWebsites:[]
}
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 += `<div class="collects">
Title: ${item.title} <br>
Description: ${item.description} </div>`
})
demos.innerHTML = html
}
body{
background-color: #000;
}
.collects{
width: 150px;
height: 100px;
padding: 10px 5px 10px 5px;
margin-right: 20px;
border-radius: 10px;
display: inline-block;
background-color: #fff;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CollectX</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<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>
<script src="/script.js"></script>
</body>
</html>
这里是 JSFiddle 的链接:https://jsfiddle.net/c3jgezwr/2/
P.S:我已经尝试过这个页面使用的方法:https://www.xul.fr/javascript/parameters.php
【问题讨论】:
-
你解释了你想做什么,你到目前为止做了什么(好!)但你没有解释为什么这不起作用,如果你卡住了,如果你遇到错误等等...详细说明您的问题。
-
我已经编辑了我的帖子。当用户单击 DOM 中创建的集合之一时,我想让用户将网站 Urls 保存在 collectX 数组中的collectedWebsites 数组中。我试图使用用户单击的集合的索引来获取集合,但我无法让它工作。
-
什么不起作用?分享您在调试时尝试过的内容。
-
请分享localStorage中的数据示例
-
我尝试了我在这里看到的:stackoverflow.com/questions/4656168/… 我想我可以渲染一个新的 HTML 页面,其中包含一个表单元素,以及 localStorage 中的集合索引。
标签: javascript html arrays oop data-structures