【发布时间】:2011-11-11 06:46:31
【问题描述】:
我想检查 <li> 的 ID 是否存在于 localstorage 中以提醒...
例如,li 的 id 有 item-1、item-2、item-3 等。在 localstorage 中有一个名为 id 的值,它会得到一个同名的字符串:第 1 项、第 2 项、第 3 项。我想检查,当我单击 id 为 item-2 的 li 时,该 item-2 是否存在于 localstorage 中以相应地发出警报。
这是我的 HTML:
<ul id="bxs" class="tabs">
<li id="item-1">1</li>
<li id="item-2">2</li>
<li id="item-3">3</li>
<li id="item-4">4</li>
<li id="item-5">5</li>
</ul>
... etc
这就是我的本地存储的样子:
Key: result
Value: [{"id":"item-1","href":"google.com"},{"id":"item-2","href":"youtube.com"}]
等等
我像这样附加列表:
var result = JSON.parse(localStorage.getItem("result"));
if(result != null) {
for(var i=0;i<result.length;i++) {
var item = result[i];
$("#bxs").append($("<li></li>").attr("id", item.id).html(item));
}
}
我想,当我点击<li> 来检查他们的 ID 是否在本地存储中作为“id”存在并相应地发出警报。像这样的:
$("#bxs").on('click', 'li',function() {
// if exists alert('exists') else alert('doesn't exists')
});
我试过了,但它总是提示它不存在:
var result = JSON.parse(localStorage.getItem("result"));
if(result != null) {
for(var i=0;i<result.length;i++) {
var item = result[i];
if(item.id != null) {
alert('doesnt exists');
}else {
alert('exists');
}
}
}
【问题讨论】:
标签: javascript jquery local-storage html-lists