添加和删​​除到本地存储中的收藏夹

ilm*_*lmk 6 jquery local-storage

我正在学习Jquery.现在我正在创建一个添加到收藏夹链接的列表.我想使用jquery将li值(例如html/Jquery/css)存储在本地存储上.一旦它添加到本地存储,我想将"添加到收藏夹"的文本更改为"删除".

然后,一旦我点击"删除"链接,我想再次"添加到收藏夹".

请检查此链接,我已粘贴当前代码.

谢谢.

$('.lists a').click(function(e){
    var favs = $(this).parent().html();
    alert(favs);
  $(this).text('Remove');
});
Run Code Online (Sandbox Code Playgroud)

Far*_*rlo 5

提琴手

 <ul class="list">
      <li id="pancakes">Pancakes</li>
      <li id="donuts">Donuts</li>
      <li id="cupcakes">Cupcakes</li>
      <li id="icecream">Icecream</li>
      <li id="cookies">Cookies</li>
      <li id="chocolate">Chocolate</li>
    </ul>
Run Code Online (Sandbox Code Playgroud)
.list li {
  cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
  content: ' \2605';
  color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
  content: ' \2606';
}
Run Code Online (Sandbox Code Playgroud)
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
  document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
  var id = e.target.id,
      item = e.target,
      index = favorites.indexOf(id);
  // return if target doesn't have an id (shouldn't happen)
  if (!id) return;
  // item is not favorite
  if (index == -1) {
    favorites.push(id);
    item.className = 'fav';
  // item is already favorite
  } else {
    favorites.splice(index, 1);
    item.className = '';
  }
  // store array in local storage
  localStorage.setItem('favorites', JSON.stringify(favorites));
});

// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
Run Code Online (Sandbox Code Playgroud)


Sum*_*ker 0

超文本标记语言

<ul id="FavList" class="lists">
  <li>Html5 <a href="#">Add to Fav</a></li>
  <li>Jquery <a href="#">Add to Fav</a></li>
  <li>Php <a href="#">Add to Fav</a></li>
  <li>Photoshop <a href="#">Add to Fav</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

JavaScript

if (!localStorage.getItem("LocalData")){  /*Check if, localStorage item `LocalData` is not set Yet*/
  localStorage.setItem("LocalData",$('#FavList').html());  /*Set `#FavList` HTML To LocalStorage item `LocalData`*/
}else{
  $('#FavList').html(localStorage.getItem("LocalData"));   /*Set LocalStorage item `LocalData` to `#FavList` HTML*/
}

$('.lists a').click(function(e){
  var text = $(this).text();
  $(this).text(text == "Add to Fav" ? "Remove" : "Add to Fav"); /*Toggle the text between `Add to Fav` and `Remove`*/
  localStorage.setItem("LocalData",$('#FavList').html()); /*Update localStorage item `LocalData` from `#FavList` HTML*/
});
Run Code Online (Sandbox Code Playgroud)

注意:这是有关localStoragesetItemgetItem的详细信息