简体   繁体   中英

Array with localStorage doesn't save or gets overwritten?

In order to summarize the problem I'll explain what the task is first.

So for the eastern event, we are going to add 3 bunny images across a website (different pages, same domain, same website). Once you've found and clicked on all 3 images it should open a new window with a specific URL.

Right now I managed to write the code which saves the clicks of the 3 pictures in an array and then opens the new window with an URL. But sadly it doesn't work once I change the page. The Array either didn't save in the browser storage or gets overwritten once I open a new page.

I'm not exactly sure what the issue is right now. I hope any of you could help me out.

I've tried to work with localStorage and sessionStorage but I don't think I used them properly. I'll provide you with my current code below.

Javascript

$(function(){
    var imageStore = [];
    $('.osterhasen').click(function(e){
        localStorage.id = $(this).attr('id');
        // returns index of the element in the array, if the element was not found returns false
        var imageExists = $.inArray(localStorage.id, imageStore);
        if (imageExists >= 0){
            // If element exists, do nothing
            e.preventDefault;
        } else {
            // If element doesn't exist, add element
            imageStore.push(localStorage.id);
        }

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

        localStorageimageStorage = JSON.parse(localStorage.getItem('imageStore'));

        console.log(localStorageimageStorage);

        if (localStorageimageStorage.length == 3) {
        window.open('https://www.google.ch');
        }
    });
});

HTML

<body>
    <div class="container">
      <div id="1" class="osterhasen"><img src="img/choco.png"></img></div>
      <div id="2" class="osterhasen"><img src="img/geschichte.png"></img></div>
      <div id="3" class="osterhasen"><img src="img/mitarbeiter.jpg"></img></div>
    </div>
</body>

In the end the clicks on the images should be saved in the browser storage across the whole website and once you've found all 3 images it should open a new window with a specfic URL.

Thank you very much for your time.

Best regards

You can't assign properties to localStorage like this (it doesn't exist, and you should be using it's setItem method anyway):

localstorage.id = $(this).attr('id');
var imageExists = $.inArray(localstorage.id, imageStore);

So assign id to a variable instead:

const id = $(this).attr('id');
const imageExists = $.inArray(id, imageStore);

Working version

Yes, you're overriding the key every time. To store an array as you want, you can try the following:

  $(function(){
    var imageStore = [];
    $('.osterhasen').click(function(e){

    if(localStorage.getItem('imageStore') === null){ // check if such key exists
        localStorage.setItem('imageStore', JSON.stringify([$(this).attr('id')])); // if it doesn't create an array with first item imageStore and set it to key imagestore
    } else {
        var currentStorage = JSON.parse((localStorage.getItem('imageStore')));
        if(!currentStorage.includes($(this).attr('id')){ // if id doesn't exist add it.
           currentStorage.push($(this).attr('id')); // push to new image inside of it
           localStorage.setItem('imageStore', JSON.stringify(currentStorage)); // set the key to the new value
        }

    }

    localStorageimageStorage = JSON.parse(localStorage.getItem('imageStore')); // you should have all the 3 pictures here in an array
     console.log(localStorageimageStorage);

        if (localStorageimageStorage.length == 3) {
        window.open('https://www.google.ch');
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM