記錄使用者在單頁面的點擊總次數,並在重新整理後保持計數。利用 Cookie 持久化儲存,有效期設為 1000 秒(示範用,實務可調長)。
function addCookie(name, value, seconds) {
if (!name || !value || !seconds) return;
if (isNaN(seconds)) return;
const expires = new Date();
expires.setTime(expires.getTime() + seconds * 1000);
document.cookie = `${name}=${escape(value)};expires=${expires.toGMTString()};path=/`;
}
function getCookie(name) {
const cookieString = document.cookie;
const start = cookieString.indexOf(name + '=');
if (start === -1) return null;
start += name.length + 1;
const end = cookieString.indexOf(';', start);
if (end === -1) return unescape(cookieString.substring(start));
return unescape(cookieString.substring(start, end));
}
const html = document.getElementsByTagName("html")[0];
html.onclick = function() {
let count = parseInt(getCookie('count')) + 1;
addCookie("count", count, "1000");
document.getElementById("count").innerHTML = `您點擊了${getCookie('count')}次!`;
};
// 頁面載入時初始化顯示
if (getCookie('count')) {
document.getElementById("count").innerHTML = `您點擊了${getCookie('count')}次!`;
} else {
document.getElementById("count").innerHTML = "您還沒有點擊過!";
addCookie("count", "0", "1000");
}
path=/ 確保全站同域名下可讀取,否則預設僅當前目錄。escape/unescape 處理特殊字元(現代建議 encodeURIComponent/decodeURIComponent)。parseInt 轉數字運算。html 元素捕獲全頁點擊,含空白區域。| 方案 | 優點 | 缺點 |
|---|---|---|
| localStorage | 容量大(5MB)、無過期時間、不隨請求發送 | 同步 API 可能阻塞主執行緒 |
| sessionStorage | 分頁級隔離、自動清除 | 關閉分頁即失效 |
| IndexedDB | 結構化儲存、支援索引查詢 | API 複雜、過殺於簡單計數 |