每个函数怪异的JQuery AddClass

时间:2015-12-03 16:35:00

标签: jquery local-storage

我在$('document')ready()上触发了一个jquery(1.11.1)函数,它迭代dom元素并在localStorage值上进行匹配,以便在itemID匹配时设置一些类。我的控制台日志记录显示项目是匹配的,但removeClass和addClass函数在找到匹配项时不起作用: ```

//process and highlight any existing favorites from localStorage
$('.snippet-star-box i').each(function () {
   var itemType = $(this).data('type');
   var itemId = $(this).data('id');
   var allFaves = JSON.parse(localStorage.getItem("my-faves"));
   if(allFaves){
      $.each(allFaves, function(i, item) {
          if (allFaves[i].id === itemId) {
              console.log("Matched Fave :" + itemId);
              $(this).removeClass('glyphicon-star-empty').addClass('glyphicon-star fave');
          }
      });
   }
});

控制台输出显示匹配项: Matched Fave :171 Matched Fave :170 不知道这里发生了什么。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您必须将外部每个循环中的图标dom元素存储在变量中,以便在内部每个循环中使用它,因为this不是第二个循环(闭包)中的图标dom元素,我建议你将allFaves变量移到循环之外,否则你将从每个项目的存储中获取并解析它:

var allFaves = JSON.parse(localStorage.getItem("my-faves"));
$('.snippet-star-box i').each(function () {
   var $this = $(this);
   var itemType = $this.data('type');
   var itemId = $this.data('id');
   if(allFaves){
      $.each(allFaves, function(i, item) {
          if (allFaves[i].id === itemId) {
              console.log("Matched Fave :" + itemId);
              $this.removeClass('glyphicon-star-empty').addClass('glyphicon-star fave');
          }
      });
   }
});

答案 1 :(得分:0)

请尝试添加$(item).removeClass('glyphicon-star-empty').addClass('glyphicon-star fave');而不是$(this).removeClass('glyphicon-star-empty').addClass('glyphicon-star fave');

答案 2 :(得分:0)

必须为$(this)设置一个var,以便在嵌套的每个中进行引用。嵌套每个中的$(this)指的是localStorage项: $('.snippet-star-box i').each(function () { var $item = $(this); var itemType = $(this).data('type'); var itemId = $(this).data('id'); var allFaves = JSON.parse(localStorage.getItem("my-faves")); if(allFaves){ $.each(allFaves, function(i, item) { if (allFaves[i].id === itemId) { console.log("Matched Fave :" + itemId); $item.removeClass('glyphicon-star-empty').addClass('glyphicon-star fave'); } }); } });