简体   繁体   中英

How to make counter which always will have right number when iI refresh a page

How can I make counter which always will have right number? I realize that when i refresh page "count" is 0 but I don't know how to fix it.

HTML

<button class="push">Push</button>
<h1 class="out"></h1>

JS

let push = document.querySelector('.push');
let out = document.querySelector('.out');
let count = 0

push.onclick = function(){   
    localStorage.setItem("num",count);
    count++;
    let test = localStorage.getItem("num");
    out.innerHTML = test;
}

let test = localStorage.getItem("num");
out.innerHTML = test;     

just to answer put that onclick in button tag like

<button onclick='onclick()'>Push</button> <div class='out'></div>

In JS file:

let out = document.querySelector('.out');
let count = 0

function onclick(){   
  localStorage.setItem("num",count++);
  displayNumValue();
}
function displayNumValue() {
  let test = localStorage.getItem("num");
  out.innerHTML = test;
}
//this is for first time JS load
displayNumValue();  

Declare count only if there is no value exist in local storage.

var count = localStorage.getItem("num") != null ? localStorage.getItem("num") : 0;

You are saving the value of count before increment.

push.onclick = function(){  
    count++; 
    localStorage.setItem("num",count);
    let test = localStorage.getItem("num");
    out.innerHTML = test;
}

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