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



我正在根据此示例开发本地存储功能:

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

所以"收藏夹"数组看起来像这样:

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

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

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

有可能做到吗?

我宁愿不使用jQuery,因为我必须重写此代码中使用的JS,并且在输出本地存储数据的另一个页面上也是如此。

谢谢

我看不到问题只是将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,因为它在位置 2 的字符串中找到了"ple"。如果字符串不包含搜索到的字符串 Eg:"apple.indexOf("tomato");则返回值将为 -1。您不能在数组上执行 indexOf。您可以使用indexOf()在字符串化数组中搜索索引值,但我不建议您这样做。

最新更新