我有一个按钮点击计数器,但如果我刷新页面,它会设置回'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);
});
});
关于javascript - 存储按钮点击次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335564/