最简单的方法 - 直接使用 localStorage

这种方法最简单,不需要任何服务器,点击数会保存在用户的浏览器本地中。缺点是: 如果用户清除浏览器数据,点击数会归零;且在不同设备上访问时,点击数不共享,非常适合个人学习、测试或小型演示。

静态网页统计点击数的js代码 html
(图片来源网络,侵删)

HTML 代码

创建一个 index.html 文件。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">点击数统计示例</title>
    <style>
        body {
            font-family: sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            background-color: #f0f2f5;
            margin: 0;
        }
        .counter-container {
            text-align: center;
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
        }
        #clickButton {
            font-size: 1.5em;
            padding: 15px 30px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        #clickButton:hover {
            background-color: #0056b3;
        }
        #counterDisplay {
            margin-top: 20px;
            font-size: 1.2em;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="counter-container">
        <h1>静态网页点击计数器</h1>
        <button id="clickButton">点击我!</button>
        <p id="counterDisplay">总点击次数: <span id="count">0</span></p>
    </div>
    <!-- 引入我们的 JavaScript 文件 -->
    <script src="script.js"></script>
</body>
</html>

JavaScript 代码

创建一个 script.js 文件,与 index.html 放在同一目录下。

// 1. 获取页面上的元素
const clickButton = document.getElementById('clickButton');
const countDisplay = document.getElementById('count');
// 2. 从 localStorage 获取存储的点击数,如果不存在则初始化为 0
// Number() 确保我们得到的是一个数字,而不是字符串
let count = Number(localStorage.getItem('clickCount')) || 0;
// 3. 在页面上显示当前的点击数
countDisplay.textContent = count;
// 4. 为按钮添加点击事件监听器
clickButton.addEventListener('click', () => {
    // 每次点击,计数器加 1
    count++;
    // 5. 更新页面上的显示
    countDisplay.textContent = count;
    // 6. 将新的点击数保存到 localStorage 中
    // JSON.stringify() 将数字转换为字符串进行存储
    localStorage.setItem('clickCount', JSON.stringify(count));
});

如何运行:

  1. 将上述两段代码分别保存为 index.htmlscript.js
  2. 用浏览器打开 index.html 文件。
  3. 点击按钮,你会发现数字在增加,即使你刷新页面,数字也会保留。

更专业的方法 - 结合服务器端 API

这是真实网站中常用的方法,前端负责发送点击请求,后端(服务器)负责接收、处理和存储数据,这里我们使用 Mocky 这个在线服务来模拟一个 API 端点,这样你无需自己搭建后端就能体验完整流程。

静态网页统计点击数的js代码 html
(图片来源网络,侵删)

原理

  1. 用户点击按钮。
  2. JavaScript 向一个模拟的 API 地址发送一个网络请求(POST 请求)。
  3. Mocky 服务接收这个请求,并模拟记录数据。
  4. 页面可以再发送一个 GET 请求来获取最新的点击数。

HTML 代码 (与方案一类似,稍作修改)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">API 点击数统计示例</title>
    <style>
        /* 样式与方案一基本相同 */
        body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; background-color: #f0f2f5; margin: 0; }
        .counter-container { text-align: center; background: white; padding: 40px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
        h1 { color: #333; }
        #clickButtonApi { font-size: 1.5em; padding: 15px 30px; border: none; border-radius: 5px; background-color: #28a745; color: white; cursor: pointer; transition: background-color 0.3s; }
        #clickButtonApi:hover { background-color: #218838; }
        #counterDisplayApi { margin-top: 20px; font-size: 1.2em; color: #666; }
        #status { margin-top: 10px; font-size: 0.9em; color: #888; }
    </style>
</head>
<body>
    <div class="counter-container">
        <h1>API 点击计数器</h1>
        <button id="clickButtonApi">点击我!</button>
        <p id="counterDisplayApi">总点击次数: <span id="countApi">--</span></p>
        <p id="status">状态: 等待点击...</p>
    </div>
    <script src="api_script.js"></script>
</body>
</html>

JavaScript 代码 (api_script.js)

重要提示: 在使用下面的代码之前,请先访问 Mocky,创建一个模拟的 API 端点。

  1. 选择 POST 方法。
  2. Body 部分,选择 application/json,并输入内容:{"status": "success"}
  3. 点击 CREATE 按钮,你会得到一个类似 https://designer.mocky.io/api/mockup/xxxxxxxxxxxx 的 URL。请将下面的代码中的 YOUR_MOCK_API_URL 替换为你自己的 URL。
// 1. 获取页面上的元素
const clickButtonApi = document.getElementById('clickButtonApi');
const countDisplayApi = document.getElementById('countApi');
const statusDisplay = document.getElementById('status');
// --- 请将下面的 URL 替换为你自己在 Mocky 上创建的 API URL ---
const API_URL = 'YOUR_MOCK_API_URL'; 
//  'https://designer.mocky.io/api/mockup/a1b2c3d4e5f6'
// 2. 页面加载时,从服务器获取初始点击数
// 这是一个异步操作,所以使用 async/await
async function fetchInitialCount() {
    try {
        statusDisplay.textContent = '状态: 正在获取数据...';
        // 为了演示,我们假设服务器返回的数据格式是 { "count": 123 }
        // 在真实场景中,你需要一个专门提供计数的 GET 接口
        // 这里我们用一个模拟的响应
        const response = await fetch(API_URL + '/count'); // 假设有一个 /count 端点
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        const data = await response.json();
        countDisplayApi.textContent = data.count;
        statusDisplay.textContent = '状态: 数据加载成功';
    } catch (error) {
        console.error('获取点击数失败:', error);
        // 如果获取失败,可以显示一个本地缓存值或默认值
        countDisplayApi.textContent = 'N/A';
        statusDisplay.textContent = '状态: 获取数据失败,请刷新重试';
    }
}
// 3. 为按钮添加点击事件监听器
clickButtonApi.addEventListener('click', async () => {
    statusDisplay.textContent = '状态: 正在发送点击请求...';
    try {
        // 向模拟的 API 发送 POST 请求,告知服务器有一次点击
        const response = await fetch(API_URL, {
            method: 'POST', // 指定请求方法为 POST
            headers: {
                'Content-Type': 'application/json' // 告诉服务器我们发送的是 JSON 数据
            },
            // body 中可以
静态网页统计点击数的js代码 html
(图片来源网络,侵删)