![](/img/trans.png)
[英]How to change display property using javascript and sessionStorage
[英]Javascript - How to display SessionStorage obj in HTML
我在 sessionStorage 中有 object 數據,我想通過循環將它們顯示為 HMTL 中的列表。 我如何實現這一目標?
SessionStorage.cart 數據字符串化:
[{"itemName":"WS: FaceShield, 10pcs pack","itemPrice":0,"itemQuantity":"1"},{"itemName":"Faceshield, 1 pc","itemPrice":0,"itemQuantity":"1"}]
我現在要做的是將它們再次解析為 JSON Object 后將它們顯示在列表中。
說你有
<ul id="myUL"></ul>
這是一個建議,如何在 JavaScript 中使用Array.prototype.reduce到Web API DocumentFragment可以在以后應用到一個UL
中的 ParentNode:
// Let's define our array
const arr = [
{"itemName":"WS: FaceShield, 10pcs pack","itemPrice":0,"itemQuantity":"1"},
{"itemName":"Faceshield, 1 pc","itemPrice":0,"itemQuantity":"1"}
];
// Store it into LS...
localStorage.arr = JSON.stringify(arr);
// Read it from LS
const LS_arr = JSON.parse(localStorage.arr);
// Create a helper for new elements...
const ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});
// Loop the array and create LI elements
const LIS = LS_arr.reduce((DF, item) => {
DF.append(ELNew('li', {
textContent: `Name: ${item.itemName} Price: ${item.itemPrice}`
}));
return DF;
}, new DocumentFragment());
// Once our DocumentFragment is populated - Append all at once!
document.querySelector("#myUL").append(LIS);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.