【问题标题】:Add and Remove to Favorites in local storage在本地存储中添加和删除到收藏夹
【发布时间】:2018-02-14 11:36:08
【问题描述】:

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

然后,一旦我单击“删除”链接,我想再次获得“添加到收藏夹”。

请检查 this link,我已将当前代码粘贴到此处。

谢谢。

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

【问题讨论】:

  • 用户 $(this).text($(this).text() == "Add to Fav" ? "Remove" : "Add to Fav");

标签: jquery local-storage


【解决方案1】:

jsfiddle

 <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>

.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';
}

// 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

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点。这是其中之一。

    第一个函数检查之前是否在localstorage 中保存了任何值,并相应地设置链接文本的文本。每次刷新/重新打开页面时都会运行。

    第二个函数保存/删除localstorage中的密钥。

    我使用&lt;li&gt; 的文本作为查找的键(即'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/

    要测试演示,请选择一两个项目,然后关闭并重新打开页面(或再次单击运行)。

    【讨论】:

    • 非常漂亮的解决方案。有没有办法在页面上只显示保存的项目。
    【解决方案3】:

    您好,您可以使用以下语法使用本地存储,因此只需设置“添加到收藏夹” 并单击删除按钮获取“添加到收藏夹”值。

    1. 您可以使用此语法在本地存储中设置值

      localStorage.setItem('AddToFav', "Add To Fav");
      
    2. 您可以使用此语法在本地存储中获取值

      var grdTotal= localStorage.getItem('AddToFav');
      
    3. 您可以使用此语法删除本地存储中的值

      localStorage.removeItem('AddToFav');
      

    谢谢。

    【讨论】:

      【解决方案4】:

      添加了简单的两步来添加和检查到 localStorage。

      • 检查是否已经添加到localStorage并根据字符串设置
      • 创建点击事件到收藏夹/从本地存储中删除

      您也可以在https://jsfiddle.net/1h433ykk/1/查看代码

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
      <ul class="lists">
        <li>Html5<a href="#">Favorite</a></li>
        <li>Jquery<a href="#">Favorite</a></li>
        <li>Php<a href="#">Favorite</a></li>
        <li>Photoshop<a href="#">Favorite</a></li>
      </ul>
      
      var addToFav = "Favorite";
      var remove = "Remove";
      
      /* Check for each a tag if already added to localStorage
       * .contents[0].nodevalue returns value of tag a
       */
      $('.lists a').each(function(e) {
        if (localStorage.getItem($(this).parent().contents()[0].nodeValue)) {
          $(this).html(remove);
        } else {
          $(this).html(addToFav);
        }
      });
      //create click event and check if nodeValue is already added or not and set text accordingly
      $('.lists a').click(function(e) {
        var nodeVal = $(this).parent().contents()[0].nodeValue;
        if (localStorage.getItem(nodeVal)) {
          localStorage.removeItem(nodeVal);
          $(this).html(addToFav);
        } else {
          localStorage.setItem(nodeVal, "true");
          $(this).html(remove);
        }
      });
      
      body {
        font-family: arial;
        font-size: 13px;
      }
      
      ul {
        max-width: 200px;
      }
      
      ul,
      ul li {
        padding: 0;
        margin: 0;
        list-style: none;
      }
      
      ul li {
        padding: 10px;
        border: 1px solid #CCC;
        margin: -1px 0 0 0;
      }
      
      ul li a {
        color: #cb0070;
        text-decoration: none;
        float: right;
      }
      

      【讨论】:

        【解决方案5】:

        HTML

        <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>
        

        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*/
        });
        

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

        【讨论】:

        • 这很好,但是如何在本地存储中添加和删除值?请帮助我也实现这一目标。谢谢
        • 好的,等等...我正在使用 localStorage 功能更新我的答案。 @ilmk
        • 对不起@Sumon Sarkar,在我点击添加到收藏之前它显示了所有值。并且从收藏中删除并不是从本地存储中删除。感谢您的努力。
        • 我已将id="FavList" 添加到列表中。请检查它@ilmk
        • 检查过,但仍然不能满足我的需求。谢谢
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 2020-11-23
        • 1970-01-01
        相关资源
        最近更新 更多