Incorrect addition of jQuery and HTML storage

I have a small program that you click on the button to add one coin, and if you update it, it will save your previous coins.

Only problem is that when you update it (run the violin), it shows its last coins, but when you click it Add another coin, it starts counting from scratch again.

$(document).ready(function () {
  var currentCoins = 0;
 $('#playerBank').html("Coins:" + localStorage.getItem('coins'));

 $('#click').click(function () {
    currentCoins = currentCoins+=1;

   localStorage.setItem('coins', currentCoins);

    var newCoins = localStorage.getItem('coins');
    $('#playerBank').html("Coins:" + newCoins);
    console.log("User:12920 Now has: " + newCoins + " In there bank!");
  });
});

http://jsfiddle.net/7h3s26ey/9/

+4
source share
1 answer

You need to change:

currentCoins = currentCoins+=1;

at

currentCoins = +localStorage.getItem('coins') + 1;

JsFiddle example

You set currentCoins = 0every time the page loads, when you really want to read from localStorage.

+4
source

Source: https://habr.com/ru/post/1568255/


All Articles