的細節有很多方法可以做到這一點。這是其中之一。
第一個函數檢查是否有任何值先前已保存在localstorage
中,並相應地設置鏈接文本的文本。每次頁面刷新/重新打開時都會執行此操作。
第二個函數保存/刪除localstorage
中的密鑰。
我已經使用<li>
的文本作爲查找的關鍵字(即'html5','jQuery'...等等)。您可以選擇在名稱空間前添加一個名稱空間(例如localStorage.getItem('myNamespace' + favs)
),並使用該名稱空間檢索該值,以便在需要時將其與localstorage
中的其他值分開。
var addFav = "Add to Fav";
var remFav = "Remove";
// update anchor tag text based on previous stored selections
$('.lists a').each(function(e){
var favs = $(this).parent().contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue
if (localStorage.getItem(favs) === "saved") {
$(this).text(remFav);
} else {
$(this).text(addFav);
}
});
// this function assumes that 1) <li> has at least some text outisde the <a>,
// and 2) the text is unique for every <li> - since it is used as a key in the lookup
$('.lists a').click(function(e){
// Grab the text of the parent, whilst excluding the text in the anchor tag (https://stackoverflow.com/a/14755309/1544886).
var favs = $(this).parent().contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue
if (localStorage.getItem(favs) === null) {
localStorage.setItem(favs, "saved");
$(this).text(remFav);
} else {
localStorage.removeItem(favs);
$(this).text(addFav);
}
});
<ul class="lists">
<li>Html5 <a href="#"></a></li>
<li>Jquery <a href="#"></a></li>
<li>Php <a href="#"></a></li>
<li>Photoshop <a href="#"></a></li>
</ul>
外部演示:https://jsfiddle.net/n4byghd3/1/
要測試的演示中選擇一項或兩下,然後關閉並重新打開網頁(或只是再次單擊運行)。
U ser $(this).text($(this).text()==「添加到收藏夾」? 「刪除」:「添加到收藏」); – SMA