javascript - 存储按钮点击次数

标签 javascript jquery html

我有一个按钮点击计数器,但如果我刷新页面,它会设置回'0'。如何存储输入,以便在关闭浏览器时上一个数字将保持不变?

$(function() {
  $('.counter').click(function() {
    $(this).val(parseInt($(this).val()) + 1);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" class="counter" value="0">

最佳答案

您可以使用本地存储来存储键/值对。以下是如何使用它的示例:

$(document).ready(function() {  

  //Firstly check if buttonClickCounter is in local storage from before.
  if(localStorage.getItem("buttonClickCounter") === null){
    //buttonClickCounter is not in local storage.

  }else{
    //buttonClickCounter is in local storage.
    var counter = localStorage.getItem("buttonClickCounter");   
    //insert the counter value into the HTML.   
    $('.counter').val(counter);     
  }


  $('.counter').click(function() {
    var newValue = parseInt($(this).val()) + 1;
    $(this).val(newValue);
    //store the new counter value in local storage.
    localStorage.setItem('buttonClickCounter', newValue);   
  });

});

您可以在控制台的“应用程序”选项卡下检查本地存储值,如下所示: enter image description here

关于javascript - 存储按钮点击次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335564/

相关文章:

html - 如何创建网页

html - 如何在实体化的文本内容后面设置背景幻灯片?

javascript - 从 html 页面删除缓存

javascript - 为什么 x.push[0] 没有产生错误?

javascript - Array.length 有时不会重新检查数组长度

JavaScript/jQuery : how to get HTML and display HTML, 包括标签

javascript - 获取后无法访问属性

javascript - 推特 Bootstrap 中的链接 <ul <li 不工作

javascript - Jquery Mobile 不透明度不起作用 :(

html - 响应式并排放置 6 个盒子