gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:11:27 25 4
gpt4 key购买 nike

我正在基于此示例开发一项本地存储功能:

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,因为它发现“ple”在字符串中的位置 2 处开始。如果字符串不包含搜索到的字符串,例如:"apple.indexOf("tomato");返回值为-1。您无法对数组执行indexOf。您可以使用 indexOf() 在字符串化数组中搜索索引值。但我不建议你这样做。

关于javascript - 编辑本地存储代码以向每个元素添加唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45813580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com