无法从 jQuery RSS Feed 中的 localStorage 动态替换类

Cannot replace class on the fly from localStorage in jQuery RSS Feed

本文关键字:localStorage 动态 替换 中的 Feed jQuery RSS      更新时间:2023-09-26

我正在尝试使用jQuery和HTML5 localStorage使用添加到收藏夹实用程序填充RSS提要。我试图实现的是当用户单击帖子标题上可用的glyphicon-star-empty时,它会更改为glyphicon-star(已完成(,但它应该将所选/收藏的项目存储在localStorage中,并在刷新时而不是显示glyphicon-star-empty,它应该从 localStorage 获取有关哪个项目被收藏的数据并显示glyphicon-star

我面临的问题在最后一部分。我可以将收藏夹项目存储在 localStorage 中,但我似乎找不到正确的方法在刷新页面时动态将glyphicon-star-empty替换为收藏夹项目的glyphicon-star

另一个问题是,当用户单击glyphicon-bookmark(在标题 -RSS 附近可用(时,它应该显示所有收藏的项目,并且还应该在取消选择时从 localStorage 和当前页面中删除项目(即单击 glyphicon-star (

这是完整的代码小提琴。

这是我正在处理的jQuery函数:

function blogRSS(url, container) {
var content = $('.data-content'); //console.log(content);

$.ajax({
  url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
  dataType: 'json',
success: function(data) {
  console.log(data.responseData.feed);

  $.each(data.responseData.feed.entries, function(key, value) {
    var thehtml = '<h4><a href="' + value.link + '" target="_blank">' + value.title + '</a></h4>';
    $("body").append(itemLayout);
          $('.panel-heading').last().html(thehtml);
          $('.data-content').last().html(value.content);
          $('.data-title').last().next().slideToggle(0);
      //console.log($('.panel-heading').last().html(value.title));
       //console.log($('.panel-heading').closest('.data-title').text());
       if(localStorage.favorite != null){
           arr = JSON.parse(localStorage.favorite);
           for(var i = 0; i < arr.length; i++){
              // console.log($('.panel-heading').last().text() == arr[i].title);
               if($('.panel-heading').text() == arr[i].title){
                   console.log('match');
                   $('.bkmark_icon').removeClass('glyphicon-star-empty');
                   $('.bkmark_icon').addClass('glyphicon-star');
                   //console.log('match');
               }
           }

       }
  }); $('.data-title').find('h4').addClass('panel-title');
在 for 循环

中添加这样的更改,基本上你需要遍历每个列表元素以及 for 循环数组来设置它。

   $( ".panel-heading" ).each( function( index, element ){                   
                   if($(this).text() == arr[i].title.trim()){                                            
                       $(this).next().removeClass('glyphicon-star-empty');
                       $(this).next().addClass('glyphicon-star');
                   }
          }); 

这是一个修改后的 JSfiddlehttps://jsfiddle.net/ehqefk6j/2/