0
我已經在html和javascript中創建了購物列表程序。我是初學者,不知道如何實現localstorage以存儲列表項。我插入程序的完整代碼,以更好地解釋實際上我想要在本地存儲中存儲的內容。它包括一個用於輸入項目名稱的輸入字段和一個單擊按鈕,將輸入的文本設置爲列表項目。列表項目然後有兩個圖像,一個用於標記完成,另一個用於從列表中刪除項目。因此,購物清單中的每個列表項都包含兩個圖像的子節點。不知道如何爲本地存儲做到這一點。任何幫助,請如何用javascript在本地存儲中存儲li文本和圖像
var input = document.getElementById('input');
var add = document.getElementById('add');
var list = document.getElementById('list');
var bottom = document.getElementById('bottom');
add.onclick = ShoppingList;
function ShoppingList(){
var li = document.createElement('li');
var imageDone = document.createElement('img');
var imageRemove = document.createElement('img');
imageDone.setAttribute('src', 'https://cdn0.iconfinder.com/data/icons/round-ui-icons/512/tick_green.png');
imageRemove.setAttribute('src', 'http://findicons.com/files/icons/1580/devine_icons_part_2/128/trash_recyclebin_empty_closed.png');
li.textContent = input.value;
li.appendChild(imageRemove);
li.appendChild(imageDone);
bottom.appendChild(li);
input.value = "";
input.focus();
imageDone.onclick = function(){
li.removeChild(imageRemove);
};
imageRemove.onclick = function(){
bottom.removeChild(li);
};
li.ondblclick = function(){
bottom.removeChild(li);
};
}
.container {
width: 400px;
margin: 50px auto;
text-align: center;
font-family: verdana;
}
#top, #bottom {
width: 300px;
margin: 20px auto;
}
#input {
width: 220px;
padding: 5px 0;
font-size: 16px;
outline: none;
border: 0;
border-bottom: 3px solid #84ac47;
}
#add {
width: 73px;
padding: 9px;
margin:0
outline: none;
background: #67c100;
color: #fff;
border: 0;
}
li {
list-style-type: none;
float: left;
line-height:36px;
padding: 8px 0;
font-size: 15px;
font-weight: 300;
text-align: left;
width: 300px;
margin-left:0;
padding-left:0;
border-bottom: 2px solid #eeeeee;
color: #67c100;
}
img {
float: right;
height: 35px;
width: 35px;
padding-left: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="shoppinglist.css">
<title>Shopping List</title>
</head>
<body>
<div class="container">
<h2>Shopping List</h2>
<div id='top'><!--
--><input type="text" id="input"><!--
--><button id="add">ADD</button>
</div>
<div id='bottom'>
<ul id="list"></ul>
</div>
</div>
<script src="shoppinglist.js"></script>
</body>
</html>
感謝您的答覆。你能解釋一下上面的代碼是怎麼回事嗎? – knight
@knight代碼在'items'數組中保存購物清單並將該數組保存在localStorage中,該數組需要首先進行字符串化,並在加載時從localStorage加載數組並解析該字符串,然後迭代數組並重新創建購物清單。 – jcubic
謝謝,但我看不到任何添加按鈕單擊事件。你能不能分享工作jsfiddle,讓我可以更好地瞭解真正發生的事情。再次感謝您的幫助 – knight