让网页使用10次后提示不能再使用了使用html+nodejs代码实现。需要完整代码
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>网页使用次数提示</title>
</head>
<body>
<h1>欢迎使用我们的网页</h1>
<p>您还可以使用 <span id="count">10</span> 次</p>
<button onclick="decrementCount()">使用一次</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.slim.js"></script>
<script>
const socket = io();
let count = 10;
function decrementCount() {
count--;
document.getElementById("count").textContent = count;
if (count === 0) {
socket.emit("maxUsageReached");
alert("您已经达到最大使用次数");
document.getElementsByTagName("button")[0].disabled = true;
}
}
</script>
</body>
</html>
Node.js代码:
const express = require("express");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
let connections = 0;
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
io.on("connection", (socket) => {
connections++;
console.log(`有 ${connections} 个用户连接到服务器`);
socket.on("maxUsageReached", () => {
console.log("已达到最大使用次数");
});
socket.on("disconnect", () => {
connections--;
console.log(`有 ${connections} 个用户断开连接`);
});
});
http.listen(3000, () => {
console.log("服务器已启动");
});
运行代码:
-
创建一个新目录,将上述两份代码分别存为
index.html和server.js。 -
在命令行中进入该目录,运行
npm init创建package.json文件。 -
安装所需依赖包:
npm install express socket.io --save
- 运行服务器:
node server.js
- 在浏览器中打开
http://localhost:3000,使用按钮测试网页使用次数提示功能。
原文地址: https://www.cveoy.top/t/topic/61w 著作权归作者所有。请勿转载和采集!