简体   繁体   English

显示从会话到HTML表的数组数据

[英]Displaying array data from session to html table

I've copied data of a html table on page 1 in an array obj(arrData). 我已经在数组obj(arrData)中复制了第1页html表的数据。 And i've save that arrData into the session storage. 而且我已经将arrData保存到会话存储中。 Now on page 2, how do i display the data from the arrData to the html table. 现在在第2页上,如何显示从arrData到html表的数据。 New in JS. JS的新功能。 Thanks in advance 提前致谢

在此处输入图片说明

PAGE 1 JS 第1页JS

var arrData=[];               
$("#checkout").on('click',function(){

$("#table tr").each(function(){
    var currentRow=$(this);

    var col1_value=currentRow.find("td:eq(0)").text();
    var col2_value=currentRow.find("td:eq(1)").text();
    var obj={};

    obj.col1=col1_value;
    obj.col2=col2_value;

    arrData.push(obj);
   sessionStorage.myArrData=JSON.stringify(arrData);
 });
console.log(arrData);

});

PAGE 2 第2页

<table class="table table-checkout" id="table">
<thead>
  <tr>
    <th>Item</th>
    <th>Quantity</th>
  </tr>
</thead>
<tbody>
</tbody>

PAGE 2 JS 第2页JS

var arrData = JSON.parse(sessionStorage.myArrData);

You need to use sessionStorage.setItem("foo", 12) rather than sessionStorage.foo = 12; 您需要使用sessionStorage.setItem(“ foo”,12)而不是sessionStorage.foo = 12;。

The latter is attaching a new property to the javascript object, not talking to the browser session API. 后者是将新属性附加到javascript对象,而不是与浏览器会话API通讯。 When the page reloads, the object you attached is gone. 页面重新加载时,您附加的对象不见​​了。

To get the item back, use sessionStorage.getItem 要取回该项目,请使用sessionStorage.getItem

Mozilla docs for sessionStorage including setItem and getItem 适用于sessionStorage的Mozilla文档,包括setItem和getItem

Once you've done that, you will need a way of creating new table rows in the table. 完成此操作后,您将需要一种在表中创建新表行的方法。 There are a multitude of frameworks for this purpose, but you can also build tables (with a few more steps than with other elements) yourself 有许多用于此目的的框架,但是您也可以自己构建表(步骤比其他元素多一些)

How to insert row in HTML table body in Javascript? 如何在Javascript的HTML表主体中插入行?

As I understand from above, You have data in array of objects after var arrData = JSON.parse(sessionStorage.myArrData); 从上面我了解到,在var arrData = JSON.parse(sessionStorage.myArrData);之后,对象数组中有数据var arrData = JSON.parse(sessionStorage.myArrData); , in below format.. ,格式如下。

arrData: arrData:

[
{col1:"Item1", col2:"quantity1"},
{col1:"Item1", col2:"quantity1"},
...
]

Now to display this data on Page 2 现在在第2页上显示此数据

var rows = "";
arrData.map((row)=>{
   var row = '<tr><td>'+row.col1+'</td><td>'+row.col2+'</td></tr>';
   rows = rows+row;
})
var tbody = document.queryselector('#table tbody');
tbody.innerHTML = rows;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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