javascript - 如何在 localStorage 中存储列表
问题描述
我创建了一个 CRUD 页面,并在用户键入文本时在输入中将文本添加到列表中。现在我想将该列表保存在 localStorage 中,并尝试存储它,但我在控制台日志中得到一个空对象。任何帮助,将不胜感激。
JAVASCRIPT
const addItem = function() {
let val = input.value;
if (val) {
let li = document.createElement('li');
let inner = '<h1 class="text">' + val + '</h1>';
inner += '<button class="delete">Delete</button>';
inner += '<button class="edit">Edit</button>';
li.innerHTML = inner;
container.appendChild(li);
input.value = '';
currentItem = li.firstChild;
//i want to save the below list
items = document.querySelectorAll('li');
for(let item of items){
//this return empty object
localStorage.setItem('list', JSON.stringify(item) );
console.log(localStorage)
}
for (let del of document.querySelectorAll('.delete')) {
del.addEventListener('click', deleteItem);
}
for (let edit of document.querySelectorAll('.edit')) {
edit.addEventListener('click', editItem);
}
} else {
alert('please add some text');
return;
}
}
如果需要,HTML
<div class="main">
<h2>JavaScript CRUD Bookmark</h2>
<form>
<input type="text" placeholder="search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">update</button>
</div>
</div>
解决方案
我已经采用了您的代码并将其重组为您可以完成的解决方案。请阅读我的代码注释以了解我所做的事情。
// HTML is almost the same as yours. I added a class name to the <ul>
// Generates a unique string of characters suitable for a key
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
const list = document.querySelector('.current-list'); // the <ul>
const addItem = function() {
// Get the input value
let input = document.querySelector('.add-text');
let val = input.value;
if (val) {
// 1. Create unique key
let uniqueKey = guid();
// 2. Append item to the list, visually. Note the contentEditable
// attribute. We can now click directly into the list item contents
// and change it. We can then update the storage when leaving the input.
list.innerHTML += `\n<li data-key="${uniqueKey}" contentEditable>${val}</li>`;
// 3. Set the storage key
localStorage.setItem(uniqueKey, JSON.stringify(val));
} else {
alert('please add some text');
return;
}
}
// TODO: Add update item function
// TODO: Add delete item function
document
.querySelector('#add')
.addEventListener('click', addItem);
小提琴:http: //jsfiddle.net/6mrbaL2n/
推荐阅读
- c++ - 如何在gsoap C++中对字符串进行严格验证
- python - 为 ndimage.center_of_mass 粒子跟踪创建圆形补丁
- php - 尽管 UTF-8 标头和字节顺序标记,但在 Excel 中未正确显示变音符号
- assembly - 依次得到其余部分
- java - 我想创建一个函数来找到最接近 n 的值,使得 Java 中的 32 % n = 0
- coldfusion - cfqueryparam 从输入复选框传入列表
- powerbi - 使用 DirectQuery 在 DAX 中将时间戳转换为日期
- python - 意外的 AttributeError 发生,即使它不应该发生
- pipe - 如何根据同一仪器中先前的复选框结果自动填充 REDCap 复选框
- python - 如何处理PYTHON中“页码不存在”的异常?