【问题标题】:array from localStorage and display in a table来自 localStorage 的数组并显示在表格中
【发布时间】:2021-09-05 16:24:47
【问题描述】:

我得到的数据不在正确的列中。这样做的正确方法是什么?

//store the data into localStorage


/* dynamically draw the table, this is the part that I m not getting it right. What should I do to ge the value in the right column. */

function doShowAll() {
  if (CheckBrowser()) {
    var key = "";
    var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
    var i = 0;

    for (i = 0; i <= localStorage.length - 1; i++) {
      key = localStorage.key(i);

      list += "<tr><td>" + key + "</td>\n<td>" +
        JSON.parse(localStorage.getItem(key)) + "</td></tr>\n";
    }
    if (list == "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n") {
      list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
    }
    document.getElementById('list').innerHTML = list;
  } else {
    alert('Cannot store shopping list as your browser do not support local storage');
  }
}


/*
 * Checking the browser compatibility.
 */


function CheckBrowser() {
  if ('localStorage' in window && window['localStorage'] !== null) {
    // we can use localStorage object to store data
    return true;
  } else {
    return false;
  }
}

/* 动态绘制表格,这是我没有做对的部分。我应该怎么做才能获得右栏中的值。 */

【问题讨论】:

  • 如果只有一项,为什么要将数组存储在localStorage 中?存储user 对象。
  • 您不再需要检查 localStorage 的浏览器兼容性 - 自 2008 年 IE8 以来所有主要浏览器都支持它。
  • 一切都是正确的。您没有正确呈现您的 。再次检查。标题有 3 列,但行只有 2
  • 不应该这样做:document.getElementById('list').innerHTML = list; - 因为你盲目地将数据从 localStorage 复制到 DOM,你正在向 XSS 攻击敞开大门。相反,您应该使用 DOM 的 createElement API 以安全的方式向页面添加内容 - 它也快得多。
  • @Barmar,必须转换为字符串才能存储更多数据。

标签: javascript arrays json local-storage


【解决方案1】:

解析 JSON 后,您需要提取 dataitem,以便将它们显示在单独的表格列中。

function doShowAll() {
  if (CheckBrowser()) {
    var key = "";
    var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
    var i = 0;

    if (localStorage.length == 0) {
      list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td><td><i>empty</i></td></tr>\n";
    } else {
      for (i = 0; i < localStorage.length; i++) {
        key = localStorage.key(i);
        let data = JSON.parse(localStorage.getItem(key));
        list += "<tr><td>" + key + "</td>\n<td>" +
          data[0] + "</td>" + data[1] + "</tr>\n";
      }
    }
    document.getElementById('list').innerHTML = list;
  } else {
    alert('Cannot store shopping list as your browser do not support local storage');
  }
}

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签