Why is the array empty every time on click?

北慕城南 提交于 2019-12-11 02:51:26

问题


So basically every time I click on the icon '.favorite i' it should add an object to my array. If I click the first time it adds the parent div to the array, but on the second time it deletes the first one and grabs the last parent div.

I'm working with three tabs called 'Monday', 'Tuesday' and 'Favorites'. I have a toggle icon which is an empty heart at start 'favorite i'. If I'm in Monday and click on the icon, the empty heart turns to be filled out and its parent is cloned and added to the '#fav' tab. When this happens the clone is saved to local storage. So if people refresh the page, they can still see their preferences.

When the heart is clicked in one of those cloned divs that specific div is removed from '#fav' and will also have to be removed from the array and local storage too.

To conclude, I need to save each cloned div into an array/local storage and then be able to delete each one of those from the array when these are removed from the #fav tab.

How to overcome this issue? Many thanks.

HTML

<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">
           <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>
         </div>
         <div class="box-container">
           <div class="box not-selected" id="box2">
           <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>
         </div>
       </div>
     </div>

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

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

   </div>
</div>

JS

$('div.tab-pane').on('click', '.favorite', function(e) {
  var add = $(this).parent().parent();
  add.each(function(){

    if ($(add.find('.not-selected .favorite i').hasClass('fa-heart'))) {

      var boxContent = $(add).clone(true, true);
      var showHide = $(boxContent).find(".session").addClass('selected').removeClass('not-selected');
      var get = $(boxContent).wrap('<p/>').parent().html();
      $(boxContent).unwrap();

      var tempArray = [];

      tempArray.push(get);

      var myJSONString = JSON.stringify(get);

      var parseString = $.parseJSON(myJSONString);

      var finalString = myJSONString.replace(/\r?\\n/g, '').replace(/\\/g, '').replace(/^\[(.+)\]$/,'$1').replace (/(^")|("$)/g, '');

      var final = localStorage.setItem('sessions', finalString);

      $("#fav").append(tempArray);

    };

  });
});

Fiddle: https://jsfiddle.net/itsfranhere/nbLLc3L0/44/


回答1:


Your question title is quite clear...
But your question itself and the code you provide prevents anyone to answer with full assurance.

Here is what the provided code produces, as an attempt to reproduce.

Now if I do not bother that code, which I think no one can deduct what it should do exactly...
Your question in title can be can answered by:

Simple! You declare (using var) the tempArray at every click.
That is why it do not retain the information (whatever it is supposed to retain) of the previous click.

I'm not "satisfied" of this answer to you... So if this do not answers completely your issue, please edit your question with more details. Feel free to fork the CodePen to make it look more like your project.


EDIT

From what I get of your script, you want to save "favorited" divs to localstorage. This implies you also have to remove them from localstorage and favorites tab if one is "unfavorited".

Also, you use id on "to be cloned" element. Be extremely cautious with this. An id has to be unique. So if the id is usefull (which was not obvious in the provided code), ensure you make it unique when you clone the element.

I improved you attempt to remove spaces and line feeds in what is to be saved.

Another good advise I have to give you is to use significative variable names in your code. Make your code speak by itself. Readability helps!

Here is your code, updated to do what is mentionned above. Have a close look to comments in code.

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
  localStorage.setItem('sessions', tempArray.join(""));

});

// Append item if localstorage is detected
if (localStorage["sessions"]) {
  $("#fav .spaces").append(localStorage["sessions"]);
  console.log( localStorage.getItem('sessions') );
}

Updated CodePen




回答2:


Don't save div elements in localStorage. I recommend you use an object constructor function like below to create a unique object for each [whatever] pushing these into an array then to localStorage in a try block.

localStorage.setItem('myobjects', JSON.stringify(myobjects));

// Object Constructor Functions
function Myobject(id, username, password) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.type = 'credential';
}

function duplicate(id,obj){
    var result = false;
    obj.forEach( function (arrayItem){
        if (arrayItem.id == id){
          result = true;
        }
    }); 
    return result;
}


function deleteObject(type, id){ 
    var obj = {};
    if (type === 'foo') {
        obj = myobjectwhatever;
        deleteThis(obj);
        //save  to local storage
        try {
            localStorage.setItem('myobject', JSON.stringify(myobjects));
        }
        catch (e) {
            console.log(e);
        }
    }
    else if (type === 'bar') {
       //...
    }

    function deleteThis(o){
        try {
            for (var i = 0, iLen = o.length; i < iLen; i++) {
                if (o[i].id === id) {
                    o.splice(i, 1);
                }
            }
        }
        catch (e) {
            console.log(e);
        }
    }
}


来源:https://stackoverflow.com/questions/46146758/why-is-the-array-empty-every-time-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!