按钮显示本地存储值

问题描述 投票:0回答:1

我有代码可以检测到当您单击按钮时,它会增加一个值并显示它 在按钮的内部文本中

var clicks = localStorage.getItem("taps");

// checks if there is no value called taps, if there is none, add one and set it to zero
if (!clicks) {
  localStorage.setItem("taps", "0");
}

// getting the button from the document
var btn = document.getElementById("clicker");

// loads the amount of taps the user has
var clicksInt = parseInt(localStorage.getItem("taps"));
localStorage.setItem("clicks", clicksInt);
btn.innerText = `${clicksInt}`

btn.onclick = function() {
  // increases the amount of taps by one and saves it to local storage
  var clicksInt = parseInt(localStorage.getItem("taps"))
  localStorage.setItem("taps", ++clicksInt)
  btn.innerText = `${clicksInt}`
}

虽然,当我运行此代码时,即使我单击它,它仍然显示零。

我尝试将 ++ 放在“clicksInt”的另一侧,如下所示:

localStorage.setItem("taps", clicksInt++)

虽然没有成功。

javascript
1个回答
0
投票

我不会在奇怪的地方改变值,而是尝试这样更明显的事情。

btn.onclick = function() {
  var clickIncrement = parseInt(localStorage.getItem("taps")) + 1
  localStorage.setItem("taps", clickIncrement)
  btn.innerText = `${clickIncrement}`
}
© www.soinside.com 2019 - 2024. All rights reserved.