首页 > 解决方案 > 从 localStorage 中检索数据并将其显示在表中

问题描述

我正在尝试从 localStorage 检索数据并展示表中的所有条目,但我无法访问密钥。

最后console.log显示特定条目。myFunction() console.log显示所有条目,但是当我尝试return所有条目时,Cannot read property 'KlientoNr'出现错误。在第二个<td>我试图直接访问条目,但我得到undifiend. 如何正确显示表格的所有条目?

jQuery(document).ready(function($) {
  const clients = JSON.parse(localStorage.getItem("data"));
  const odontologas = clients.Odontologas;

  const myFunction = () => {
    const arrayLength = odontologas.length;
    for (var i = 0; i < arrayLength; i++) {
      console.log(odontologas[i].KlientoNr);
    }
    return odontologas[i].KlientoNr;
  };

  $.each(odontologas, function() {
    $("#odontologas").append(`<tr>
      <td>${myFunction()}</td>
      <td>${odontologas.EilėsNr}</td>
      <td>
        <button type="submit" class="btn btn-success">
          Aptarnautas
        </button>
      </td>
    </tr>`);
  });
  console.log(odontologas[7].KlientoNr);
});

标签: javascriptjqueryajax

解决方案


的问题${odontologas.EilėsNr}odontologas整个数组并且没有属性EilėsNr

使用传递给每个回调的参数来访问特定的对象实例

 $.each(odontologas, function(i, item) {
    $("#odontologas").append(`<tr>
      ...
      <td>${item.EilėsNr}</td>
      // OR
      <td>${odontologas[i].EilėsNr}</td>
      ...

推荐阅读