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

时间:2017-09-12 03:09:44

标签: 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"] );
}

小提琴:https://codepen.io/Bes7weB/pen/bobjdv?editors=1011

1 个答案:

答案 0 :(得分:1)

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

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

现在,在页面加载时......如果存储中的收藏夹数量超过零,请通过从存储中加载类来应用图标状态。你已经有了这个部分。 那么循环通过所有人的心脏来定位已填充的那些并在喜欢的标签中克隆它们。我做了一个&#34;命名函数&#34;这样做。

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

在原始元素上,您希望切换其类并将其克隆到收藏夹选项卡。所以在这里,只需进行切换和收藏选项卡,只需调用上一个命名函数即可克隆它们!

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

注意不再使用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