繁体   English   中英

Javascript - 如何在 HTML 中显示 SessionStorage obj

[英]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.reduceWeb 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM