以下是您想要使用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