我有这个基本功能:
pid = 1;
$(function() {
if (localStorage["key"+pid] != null) {
var contentsOfDiv = localStorage.getItem("key"+pid);
$("#Div").html(contentsOfdDiv);
}
});
问题是pid
值最终会发生变化,我不想覆盖key
的内容。
如何继续堆叠Div
为我保存的每个localStorage
内容?
答案 0 :(得分:5)
您可以像在任何对象属性上一样迭代localStorage条目:
for (var key in localStorage) {
console.log(key, localStorage[key]);
}
所以你的代码可能是:
$(function() {
var lines = [];
for (var key in localStorage) {
if (/^key/.test(key)) { // does the key start with "key"
lines.push(key.slice(3) + ' = ' + localStorage[key]);
}
}
$("#Div").html(lines.join('<br>'));
});
答案 1 :(得分:0)
如果我理解得很好,你想用pid循环遍历对象。
这样做的最佳方法是避免链原型问题如下:
(对于这种情况,我认为你使用数组而不是对象更好)
var localStorage = ['aaaa', 'bbbbb', 'cccc', 'dddd']; // don't forget to declare with var
var html_string = '';
$.each(localStorage, function(index, value) {
html_string += value + '<br>';
});
$('#my_div').html(html_string);