如何使用localStorage存储点击次数

时间:2018-01-11 13:50:48

标签: javascript

我正在尝试使用localStorage保存文本框中按钮的点击次数,但每当我重新加载页面时,所有数据都会被清除。这是我的代码:

var i = 0;  // i is the number of clicks. the number of clicks is set to 0 
when page is
// loaded.
function countClick() { // The next 3 lines of code are executed when the 
Kill a cat     // button is clicked
i++;

alert("You have clicked " + i + " cats so far"); // Make message box
localStorage.setItem("count", "i")
document.getElementById("count").value = i ; // Edits the 'clicks clicked' 
text box
// Saves number of clicks, so when you close      // or open the page, your 
progress still exists.

}
function clear() {
  document.getElementById("count").value = 0 ;
}

window.onload = function(){
  var val = localStorage.getItem('value'); // or localStorage.value

  if(val === null)
      val = "i";

 document.getElementById("myData").value = val;
}
window.onbeforeunload = function(){
localStorage.setItem('value', document.getElementById("myData").value);  
localStorage.value = document.getElementById("myData").value
}

请帮忙。

感谢其他人的所有其他例子,在这里使用。

1 个答案:

答案 0 :(得分:0)

在此功能中,您在页面加载之前重置localStorage项目...

window.onbeforeunload = function(){
localStorage.setItem('value', document.getElementById("myData").value);  
localStorage.value = document.getElementById("myData").value
}

正常,刷新时没有数据。 如果没有其他功能,只需尝试更简单的事情:

var i = 0;

function countClick() { 

i++;
localStorage.setItem("count", i)
document.getElementById("count").value = i ; 

}

window.onload = function(){
  var val = localStorage.getItem('count'); 

 document.getElementById("count").value = val;
}