![](/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.