【发布时间】:2018-12-03 11:17:03
【问题描述】:
我是 node.js 和 socket.io 的新手。我想实现一个简单的功能,当套接字单击按钮时,该按钮的背景颜色将切换为蓝色。
这是我的客户端 html 代码:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
</head>
<style type="text/css">
.blue {
background: blue;
}
</style>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function(){
var socket = io();
$("button").click(function(){
socket.emit("click button");
return false;
});
socket.on("click button", function(){
$("button").toggleClass("blue");
});
});
</script>
<body>
<button>Click me to change</button>
<br>
<button>Don't change me</button>
</body>
</html>
这是我的 server.js 文件:
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server);
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
io.on("connection", function(socket){
socket.on("click button", function(){
io.emit("click button");
})
});
server.listen(process.env.PORT, process.env.IP, function(){
console.log("The server is now starting......");
});
当然,这段代码不能工作,因为它在单击一个按钮时会切换所有按钮。但我想知道只切换被点击的按钮的正确方法是什么?
感谢您的任何建议!
【问题讨论】:
-
将
ids 添加到您的按钮,并将被点击的按钮的ID ($(this).attr('id')) 发送到您的io.socket。在您的套接字 (socket.on()) 的 subscribe 方法中,从事件/有效负载中读取 id,并使用它通过使用 jQuery 选择器中的 id 只为相应按钮调用toggleClass(实现这一点留给问题作者作为练习????) -
谢谢摩羯座!非常有用的建议