以下是您想要使用SessionStorage的示例。即使刷新页面,点击计数器也会持续存在。
另外,在每次点击时,您都可以将其存储在服务器上。
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>
您还可以使用localStorage的这种情况。本地存储更安全,大量数据可以存储在本地,而不会影响网站性能。
与Cookie不同,存储限制要大得多(至少5MB),并且信息永远不会传输到服务器。
下面是一个例子
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
</body>
</html>
您好,欢迎堆栈溢出,请花时间去通过[欢迎参观(https://stackoverflow.com/tour)了解你在这里的方式(并获得你的第一个徽章),阅读如何创建[mcve]示例,并检查[问],以便增加获得反馈和有用答案的机会。 – garfbradaz