の詳細であるこれを行うための方法はたくさんあります。ここにその1つがあります。
最初の関数は、値がlocalstorage
に以前に保存されているかどうかをチェックし、それに応じてリンクテキストのテキストを設定します。これは、ページがリフレッシュ/再オープンされるたびに実行されます。
第2の機能は、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/
デモがアイテムまたは2、[閉じる]を選択し、ページを再度開く(または単に再実行]をクリックします)テストします。
U $(this).text($(this).text()== "Favに追加"? "Remove": "Favに加える"); – SMA