在表

时间:2018-05-13 04:44:02

标签: javascript jquery html

所以我目前将它存储在我的localStorage中:

{cart: "[{"Author":"Micheal Grant","title":"Gone"},{{"Author":"Micheal 
Grant","title":"Fear"}]"

我只是想知道如何检索这些数据并将其显示在表格中:

例如:

<table border="1">
  <tbody>
    <tr>
      <th> Book Title </th>
      <th> Author </th>
    </tr>
    <tr>
      <td class="Book_Title">Gone </td>
      <td class="Author">Micheal Grant</td>
    </tr>
    <tr>
      <td class="Book_Title">The Knife of never letting go</td>
      <td class="Author">Ryan Howard</td>

    </tr>
 </tbody>
</table>

3 个答案:

答案 0 :(得分:0)

好的,这就是你应该做的事情

var cart= JSON.parse( localStorage.getItem('cart' ) );
    $.each(cart, function(key, value){
      $('tbody').append(`<tr>
      <td class="Book_Title">${cart.title}</td>
      <td class="Author">${cart.Author}</td>
    </tr>`)
})

答案 1 :(得分:0)

localStorage.getItem(dataObj);这样的localStorage中检索项目后,您可以使用jQuery的each()来遍历所有项目。在处理程序函数内部,使用值创建tr并将其附加到tbody

请注意在append()内使用Template literals

尝试以下方式:

&#13;
&#13;
//localStorage.getItem(dataObj);
var jsonData = {cart: [{"Author":"Micheal Grant","title":"Gone"},{"Author":"Micheal Grant","title":"Fear"}]};

$.each(jsonData.cart, function(key, value){
  $('tbody').append(`<tr>
  <td class="Book_Title">${value.title}</td>
  <td class="Author">${value.Author}</td>
</tr>`);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tbody>
    <tr>
      <th> Book Title </th>
      <th> Author </th>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用localStorage功能从localStorage.getItem检索数据。

获得数据后,遍历cart属性,并使用javascript template strings创建html结构。使用模板字符串的优点是它更具可读性,您可以使用${}轻松地在其中插入javascript变量。

//localStorage.getItem(dataObj);
var data = {
  cart: [{
    "Author": "Micheal Grant",
    "title": "Gone"
  }, {
    "Author": "Micheal Grant",
    "title": "Fear"
  }]
};

var tableData = data.cart.map(book => (
  `
    <tr>
      <td>${book.title}</td>
      <td>${book.Author}</td>
    </tr>
  `
)).join('');

var tbody = document.querySelector('#body');
tbody.innerHTML = tableData;
<table border="1">
  <thead>
    <tr>
      <th> Book Title </th>
      <th> Author </th>
    </tr>
  </thead>
  <tbody id="body">
  </tbody>
</table>