1

I'm in the middle of my school project and i can't seem to find a solution for a bug i have:

I'm setting cards to local storage, and i have a "delete" option on the card itself which allows me to remove items off local storage (by splice(x)) and from the initial array itself. The delete option seems to work just fine after i get the items from the storage but somehow it's not working on new items before i refresh the page.

What am i doing wrong??

this is my delete function:

function dispose(x, arr, index) {
var disOne = document.getElementsByClassName('dispose')[x];
disOne.addEventListener('click', function (event) {
    this.parentElement.parentElement.parentElement.style.display = 'none';
    arr.splice(index, 1);
    window.localStorage.setItem('Cards_', JSON.stringify(arr));
})

}

My get from storage function - which works great!

function getFromStorage() {
var savedCards = JSON.parse(window.localStorage.getItem('Cards_'));
for (var j = 0; j < savedCards.length; j++) {
    createCard(savedCards[j]);
    dispose(j, savedCards, j);   
    allCards=savedCards;
}

}

And my problem::

createCard(oneCard);
allCards.push(oneCard);
setToLocalStorage(allCards);

for(var i=0;i<allCards.length;i++){
dispose(i,allCards,i)
}

can someone please explain where the misstake is?

I.singat
  • 11
  • 1
  • See the referenced Q&A: the problem is that splice will move elements to a lesser index, and so previously passed index arguments to `dispose` no longer point to the correct entry. A second click will remove the wrong -- or no -- element as a consequence. – trincot Nov 10 '18 at 18:09
  • Thanks, tried to change the dispose() index to move allong with the array length by looping backwards - did not work. Is it possible to solve without looping? Or any other suggestions? – I.singat Nov 12 '18 at 05:18

0 Answers0