localStorage 应该替换哪些元素?

问题描述 投票:0回答:1

我想为我的 Tumblr 博客创建一个点击计数器。但由于我使用的是 localStorage,因此无法显示所有客户端号码。我应该用什么来代替它?谢谢你!
代码

var visitCount = localStorage.getItem("page_view");

if (visitCount) {
  visitCount = Number(visitCount) + 1;
  localStorage.setItem("page_view", visitCount);
} else {
  visitCount = 1;
  localStorage.setItem("page_view", 1);
}
counterContainer.innerHTML = visitCount;
javascript tumblr tumblr-themes hitcounter tumblr-html
1个回答
0
投票

如果我理解正确的话...

您在使用

localStorage
的点击计数器时遇到的问题可能是由于
localStorage
仅在客户端存储数据,并且它特定于每个客户端的浏览器。 这意味着,如果用户从

不同的设备或浏览器

访问您的 Tumblr 博客,点击计数器将不会显示统一的计数。 以下是如何实现这一目标的基本概述:

    设置服务器:
  1. 您需要一个服务器来处理点击计数。您可以使用网络托管服务或云服务器来实现此目的。
  2. 数据库:
  3. 设置数据库来存储点击次数。您可以使用 MySQL、PostgreSQL 等流行数据库,或 MongoDB 等 NoSQL 数据库。
  4. Tumblr 集成:
  5. 在您的 Tumblr 博客代码中,向服务器的 API 端点发出请求以检索点击计数并将其显示在您的博客上。
  6. 这是一个使用
Node.js 和 Express.js

来实现 服务器端 代码的高级示例:

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); // Connect to your database mongoose.connect('mongodb://localhost/hitcounterdb'); // Create a schema and model for hit counts const hitCountSchema = new mongoose.Schema({ count: Number, }); const HitCount = mongoose.model('HitCount', hitCountSchema); app.use(bodyParser.json()); // Endpoint to get the hit count app.get('/api/hitcount', async (req, res) => { try { const hitCount = await HitCount.findOne(); if (!hitCount) { res.json({ count: 0 }); } else { res.json({ count: hitCount.count }); } } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }); // Increment the hit count app.post('/api/increment', async (req, res) => { try { let hitCount = await HitCount.findOne(); if (!hitCount) { hitCount = new HitCount({ count: 1 }); } else { hitCount.count++; } await hitCount.save(); res.json({ count: hitCount.count }); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

© www.soinside.com 2019 - 2024. All rights reserved.