Localstorage:如果< li>的ID存在于localstorage警报中 [英] Localstorage: If the ID of a <li> exists in localstorage alert
问题描述
我想检查localstorage中是否存在< li>
的ID以提醒...
I want to check if the ID of a <li>
exists in localstorage to alert...
例如,li有id,例如item-1,item-2,item-3等。在localstorage中有一个名为 id 的值,它获取一个具有相同名称的字符串:item -1,item-2,item-3。我想检查,当我点击带有id item-2的li时,如果item-2存在于localstorage中以进行相应的警报。
For example, the li's have id such as item-1, item-2, item-3 etc. In localstorage there is a value named id and it gets a string with the same name: item-1, item-2, item-3. I want to check, when I click on a li with id item-2, if that item-2 exists in localstorage to alert accordingly.
这是我的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
这就是我的localstorage的样子:
And this is what my localstorage looks like:
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是否在localstorage中作为 id 存在并相应地发出警报。这样的事情:
and I want, when I click on the <li>
's to check if their ID exists as an 'id' in localstorage and alert accordingly. Something like this:
$("#bxs").on('click', 'li',function() {
// if exists alert('exists') else alert('doesn't exists')
});
我试过这个,但它总是警告它不存在:
I tried this but it always alert that it 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');
}
}
}
推荐答案
在这里
$("#bxs").on('click', 'li',function() {
var exists = false
for(var i=0;i<result.length;i++) {
var item = result[i];
if(item.id == $(this).prop("id")) {
exists = true;
break;
}
}
if(exists) {
alert("exists");
}
else {
alert("doesn't exists");
}
});
这篇关于Localstorage:如果< li>的ID存在于localstorage警报中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!