【发布时间】: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 的createElementAPI 以安全的方式向页面添加内容 - 它也快得多。@Barmar,必须转换为字符串才能存储更多数据。
标签: javascript arrays json local-storage