【问题标题】:Localstorage: If the ID of a <li> exists in localstorage alertLocalstorage:如果 <li> 的 ID 存在于 localstorage 警报中
【发布时间】:2011-11-11 06:46:31
【问题描述】:

我想检查 &lt;li&gt; 的 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));

    }
}

我想,当我点击&lt;li&gt; 来检查他们的 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


    【解决方案1】:

    你来了

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-26
      • 2014-01-31
      • 2019-11-07
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      相关资源
      最近更新 更多