javascript - 为什么持久数据不能正常工作?

标签 javascript jquery onclick save storage

我正在使用三个名为“星期一”、“星期二”和“收藏夹”的选项卡。我有一个切换图标,在“最喜欢的我”开头是一颗空心的图标。如果我在星期一点击该图标,空心的心就会被填充,其父心会被克隆并添加到“#fav”选项卡中。发生这种情况时,克隆将保存到本地存储。因此,如果人们刷新页面,他们仍然可以看到自己的偏好。

当在这些克隆的 div 之一中单击心形时,特定的 div 将从“#fav”中删除,并且也会从数组中删除。

一切正常,除了当我刷新浏览器并检测到本地存储时。

所以,在这种情况下,如果我在星期一点击一颗填满的心,它不会从 #fav 中删除克隆,并且仍然会向 #fav 添加一个新的克隆。另外,如果我在 #fav 选项卡中,当单击其中一颗心时,它应该从数组中删除索引,但实际上,它会删除整个数组。

如何解决这个问题?非常感谢。

HTML:

<section id="speakers-programme">
  <div class="container">
    <div class="tabs_main">

      <div class="col-md-5"><a data-target="#mon" class="btn active" data-toggle="tab">Monday</a></div>
      <div class="col-md-5"><a data-target="#tue" class="btn active" data-toggle="tab">Tuesday</a></div>
      <div class="col-md-2"><a data-target="#fav" class="btn active" data-toggle="tab"><i class="fa fa-heart" aria-hidden="true"></i></a></div>

    </div>

    <div class="tab-content">
      <div class="tab-pane active" id="mon">
        <br>
        <div class="spaces">
          <div class="box-container">
            <div class="box not-selected" id="box1">
              <span>1</span>
              <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>
            </div>
          </div>
          <div class="box-container">
            <div class="box not-selected" id="box2">
              <span>2</span>
              <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>
            </div>
          </div>
        </div>
      </div>

      <div class="tab-pane active" id="tue">
        <br>
        <div class="spaces">
        </div>
      </div>

      <div class="tab-pane active" id="fav">
        <br>
        <div class="spaces">
        </div>
      </div>

    </div>
  </div>
</section>

JS

console.clear();
//localStorage.setItem('sessions', "");

var tempArray = [];

// Clones
$('div.tab-pane').on('click', '.favorite', function(e) {
  e.preventDefault();

  // Elements we play with... Having significative variable names.
  var heartLink = $(this);
  var box = heartLink.parent('.box');
  var container = box.parent('.box-container');
  var favoriteTab = $("#fav .spaces");

  // I don't know what is the use for those 3 lines below.
  var idFind = box.attr("id");
  var idComplete = ('#' + idFind);
  console.log(idComplete);

  //TOGGLE FONT AWESOME ON CLICK
  heartLink.find('i').toggleClass('fa-heart fa-heart-o'); // .selected or not, you need those 2 classes to toggle.
  box.toggleClass("selected not-selected"); // Toggle selected and not-selected classes

  // Clone div
  var boxContent = container.clone(true, true);

  // Change the id
  var thisID = boxContent.attr("id")+"_cloned";
  boxContent.attr("id", thisID);

  // Get the html to be saved in localstorage
  var get = boxContent.wrap('<p>').parent().html();
  get = get.replace(/\r?\n/g, "").replace(/>\s*</g, "><"); // remove line feeds and spaces
  console.log(get);
  boxContent.unwrap();

  // Decide to add or remove
  if(box.hasClass("selected")){
    console.log("Add to array")
    tempArray.push(get);

    // Add to favorites tab
    favoriteTab.append(boxContent);

  }else{
    console.log("Remove from array");
    var index = tempArray.indexOf(get);
    tempArray.splice(index);

    // Remove from favorite tab
    favoriteTab.find("#"+thisID).remove();
  }

  // Save array
  localStorage.setItem('sessions', tempArray.join(""));
  console.log(tempArray);

  // save this current toggle state
  localStorage.setItem(box.attr("id"), $(this).find("i").attr("class"));
  console.log($(this).find("i").attr("class"));

});

// Append item if localstorage is detected
if (localStorage["sessions"]) {
  console.log("storage exist");

  // Load 
  $(".box").each(function(){
    console.log( $(this).attr("id") );
    console.log( localStorage.getItem($(this).attr("id")) );

    if(localStorage.getItem($(this).attr("id")) != null){
      $(this).find("i").removeClass().addClass( localStorage.getItem($(this).attr("id")) );
    }
  });

  $("#fav .spaces").append(localStorage["sessions"]);
  console.log( localStorage["sessions"] );
}

fiddle :https://codepen.io/Bes7weB/pen/bobjdv?editors=1011

最佳答案

我以一种值得解释的方式扭曲了你的代码。

首先,您终于不需要保存您喜爱的元素的 HTML 了。您只需要心形图标状态,您已经这样做了。我添加了一个计数器,只是为了知道存储中有多少个收藏夹。

现在,在页面加载时...如果存储中的收藏夹数量超过零,则通过从存储中加载其类来应用图标状态。这部分你已经做对了。 然后循环遍历所有心形,以定位填充的心形并将它们克隆到最喜欢的选项卡中。我创建了一个“命名函数”来执行此操作。

立即单击图标...单击克隆元素或原始元素是两种不同的情况。

在原始元素上,您想要切换其类并将其克隆到最喜欢的选项卡。因此,在这里,只需进行切换,对于最喜欢的选项卡,只需调用先前命名的函数即可将它们全部克隆!

在克隆的元素上,您希望将其从收藏夹中删除并切换原始元素类。请参阅代码来获得我所做的这个扭曲!在这种情况下,我重新定义了一些变量。

注意不再使用tempArray
;)

var favoriteTab = $("#fav .spaces");

// Named function to load the favorites tab
function loadFav(){
  // First, clear old favorites.
  favoriteTab.empty();

  // Look for filled hearts
  var favCount = 0;
  $(".tab-content").find("i.fa-heart").each(function(){
    // Count them
    favCount++;
    // Clone its box
    var favClone = $(this).closest(".box").clone();
    // Change the id
    favClone.attr("id", favClone.attr("id")+"_clone");
    // Append to favorites
    favoriteTab.append(favClone);
  });

  console.log("favCount: "+favCount);
  localStorage.setItem("favAmount", favCount);
}

// Click handler
$('div.tab-pane').on('click', '.favorite', function(e) {
  e.preventDefault();

  // Elements we play with... Having significative variable names.
  var heartLink = $(this);
  var box = heartLink.parent('.box');
  var thisID = box.attr("id");
  var container = box.parent('.box-container');

  if(thisID.split("_")[1] == "clone"){
    console.log("You clicked a clone!");
    // Remove that clone
    box.remove();
    // Use the original element for the rest of the function.
    heartLink = $("#"+thisID.split("_")[0]).find("a.favorite");
    box = heartLink.parent('.box');
    thisID = box.attr("id");
  }

  //TOGGLE FONT AWESOME ON CLICK
  heartLink.find('i').toggleClass('fa-heart fa-heart-o'); // .selected or not, you need those 2 classes to toggle.
  box.toggleClass("selected not-selected"); // Toggle selected and not-selected classes

  // Clone div
  loadFav();

  // Save this current toggle state
  localStorage.setItem(box.attr("id"), heartLink.find("i").attr("class"));
  console.log(heartLink.find("i").attr("class"));

});




// ON PAGE LOAD
// Append item if localstorage is detected
if (localStorage["favAmount"]>0) {
  console.log("storage exist");

  // Load heart's element states
  $(".box").each(function(){
    console.log( $(this).attr("id") );
    console.log( localStorage.getItem($(this).attr("id")) );

    if(localStorage.getItem($(this).attr("id")) != null){
      $(this).find("i").removeClass().addClass( localStorage.getItem($(this).attr("id")) );
    }
  });

  // Load favorites
  loadFav();

}else{
  console.log("no storage");
}

CodePen v6

关于javascript - 为什么持久数据不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46167293/

相关文章:

javascript - 在 2.15.1 ember-cli 版本中远离 Bower

javascript - 未选择检测元素

javascript - 设置overflow-y滚动条的样式

JQUERY - $.get(url,data,function(data) ,'html' ) 不适用于 IE

javascript - 由于 html anchor 中的 onclick 事件导致页面加载缓慢

JavaScript 数组 ["index"].push() 不起作用

javascript - 防止在特定代码段中调用函数

javascript - 当用户完成输入时验证用户输入

javascript - JQuery PHP/HTML 切换 onclick

Android:你如何让按钮在一段时间内不可点击?