简体   繁体   English

带有 localStorage 的数组不保存或被覆盖?

[英]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).因此,对于东部活动,我们将在一个网站上添加 3 个兔子图像(不同的页面、相同的域、相同的网站)。 Once you've found and clicked on all 3 images it should open a new window with a specific URL.找到并单击所有 3 个图像后,它应该会打开一个带有特定 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.现在我设法编写了将 3 张图片的点击次数保存在一个数组中的代码,然后使用 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. Array 要么没有保存在浏览器存储中,要么在我打开新页面后被覆盖。

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.我尝试使用 localStorage 和 sessionStorage,但我认为我没有正确使用它们。 I'll provide you with my current code below.我将在下面为您提供我当前的代码。

Javascript 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 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.最后,对图像的点击应该保存在整个网站的浏览器存储中,一旦找到所有 3 张图像,它应该打开一个带有特定 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分配属性(它不存在,你应该使用它的setItem方法):

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

So assign id to a variable instead:所以将id分配给一个变量:

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');
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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