Localstorage: If the ID of a <li> exists in localstorage alert

家住魔仙堡 提交于 2019-12-08 10:04:51

问题


I want to check if the ID of a <li> exists in localstorage to alert...

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.

This is my 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

And this is what my localstorage looks like:

Key: result

Value: [{"id":"item-1","href":"google.com"},{"id":"item-2","href":"youtube.com"}] 

etc.

I append the list like this:

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));

    }
}

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');

                }
            }
        }

回答1:


here you are

$("#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");
    }
});


来源:https://stackoverflow.com/questions/8087126/localstorage-if-the-id-of-a-li-exists-in-localstorage-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!