简体   繁体   中英

How to store a newly created element to localStorage or Cookie with Javascript?

I am making an idle clicker game for fun, everything was going fine until I encountered a problem.

What I basically want to happen is when the image is clicked and the clickCounter element is over one, the new image element is created. No problem here, the main problem is saving the image. If the user refreshes the page, I want the created element to still be there . I have tried using outerHTML and following some other Stack Overflow forum questions but I could never get a proper solution to this certain problem. I have also tried localStorage and cookies but I believe I am using them wrong.

My code is below, my sololearn will be linked below, consisting of the full code to my project.

 function oneHundThou() {

   var countvar = document.getElementById("clickCounter")
    if(document.getElementById("clickCounter").innerHTML > 1) {
      alert("Achievement! 1 pat!")
      
      var achievement1k = document.createElement("img");
     

      // create a cookie so when the user refreshes the page, the achievement is shown again 

      document.cookie = "achievement1k=true";
      achievement1k.src = "https://c.pxhere.com/images/f2/ec/a3fcfba7993c96fe881024fe21e7-1460589.jpg!d";
      
      achievement1k.style.height = "1000px"
      achievement1k.style.width = "1000px"
      achievement1k.style.backgroundColor = "red"
      
      document.body.appendChild(achievement1k);
      oneHundThou = function(){}; // emptying my function after it is run once instead of using a standard switch statement
    }
    else {
      return
    }

  }
  oneHundThou();
  

I am aware that there is another post that is similar to this, however, my answer could not be answered on that post.

Full code is here: https://code.sololearn.com/Wwdw59oenFqB Please help! Thank you. (:

Instead of storing the image, try storing the innerHTML , then create the image on document load:

function oneHundThou() {
  countvar.innerHTML = localStorage.getItem('clickCount') ? localStorage.getItem('clickCount') : 0; //before if
  //original code
  localStorage.setItem('clickCount', countvar.innerHTML); //instead of doc.cookie
}

window.addEventListener('DOMContentLoaded', (event) => {
    oneHundThou();
});

or, if you don't care that clickCounter may initialize to null , you can remove the ? : ? : and just put

countvar.innerHTML = localStorage.getItem('clickCount');

Edit: shortened code with the countvar variable

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