我正在基於這個例子一塊本地存儲功能:編輯本地存儲代碼的唯一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)' –
謝謝 - 工作。我還有一個問題 - 你可以看看我可以然後檢查數組,看看是否該項目/值存在於數組中,因爲每次單擊一個列表項時,現有的'index = favorites.indexOf(id);'行總是返回'-1' - 似乎將下一個插入到「name」元素/鍵中意味着indexOf找不到它? – 4532066
我爲這兩個請求都寫了一個答案 –