编辑本地存储代码以向每个元素添加唯一ID

时间:2017-08-22 09:18:36

标签: javascript local-storage

我正在根据此示例处理一个本地存储功能:

https://scriptscodes.com/codes/CrocoDillon/pIlKB/preview/index.html

CSS:

/* https://scriptscodes.com/codes/CrocoDillon/pIlKB/preview/index.html */
.list li{
    cursor:pointer;
}

.list li:before,.list li.fav:before {
    font-family: FontAwesome;
    content:"\f08a";
    color:white;
    margin-right:10px;
    font-size:14px;
}

.list li:hover:before {
    font-family: FontAwesome;
    content:"\f004";
    color:white;
    margin-right:10px;
    font-size:14px;
}

.list li.fav:hover:before,.list li.fav:before {
    font-family: FontAwesome;
    content:"\f004";
    color:red;
    margin-right:10px;
    font-size:14px;
}

示例HTML:

<div class="list" style="background:#ccc; padding:20px;">
    <ul class="list-unstyled">
        <li id="petty">petty</li>
        <li id="bedfordshire">bedfordshire</li>
        <li id="rearing">rearing</li>
        <li id="jane">jane</li>
        <li id="furore">furore</li>                         
    </ul>
</div>

然后我可以使用以下内容将每个项目添加到本地存储:

JS:

var favorites =   JSON.parse(localStorage.getItem('favorites')) || [];

document.querySelector('.list').addEventListener('click', function(e) {
    var id = e.target.id,
        item = e.target,
        index = favorites.indexOf(id);
    if (!id) return;
    if (index == -1) {
        favorites.push(id);
        item.className = 'fav';
    } else {
        favorites.splice(index, 1);
        item.className = '';
    }
    localStorage.setItem('favorites', JSON.stringify(favorites));
});

使用此代码的测试页面位于:https://jimpix.co.uk/testing/test3.asp

所以&#34;收藏夹&#34;数组看起来像这样:

favorites:"["petty","rearing","jane"]"

我需要弄清楚如何编辑JS,以便为每个元素赋予唯一的ID,因此数组看起来像这样:

favorites:"[{"id":"1","name":"petty"},{"id":"2","name":"rearing"},{"id":"3","name":"jane"}]"

有可能吗?

我不想使用jQuery,因为我必须重写此代码中使用的JS,以及我输出本地存储数据的另一个页面。

由于

1 个答案:

答案 0 :(得分:2)

我无法看到问题只是将favorites.push({ id: 1, name: "petty" }推入您的阵列并在之后进行字符串化?对于唯一ID,请使用for循环的索引或尝试以下内容:Math.floor(window.performance.now() * 1000)

要查找元素是否在数组中,请执行以下操作:

function isIdInArray(id) { // param id is the id youre looking for in the array
    var isInArray = false;
    favorites.forEach(function(favorite){
        if(favorite.id === id){
            isInArray = true;
        }
    });
    return isInArray;
}

为了澄清你是否要index = favorites.indexOf(id);这将搜索字符串中的字符串。 例如。 "apple".indexOf("ple");将返回2,因为它找到了&#34; ple&#34;从位置2的字符串开始。如果字符串不包含搜索的字符串Eg:"apple.indexOf("tomato");,则返回值为-1。您无法在阵列上执行indexOf。您可以使用indexOf()在字符串化数组中搜索索引值,但我不会建议您这样做。