jquery - 通过 jQuery 选择特定元素并在 socket.io 中操作
问题描述
我是 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......");
});
当然,此代码无法正常工作,因为它在单击一个按钮时会切换所有按钮。但我想知道只切换被点击的按钮的正确方法是什么?
感谢您的任何建议!
解决方案
You can use the this
keyword to select the clicked element, eg.
$("button").click(function(){
socket.emit("click button");
$(this).toggleClass("blue");
return false;
});
推荐阅读
- php - 如何过滤PHP中键的值?
- php - Why is this e-mail form using validation resulting in an error?
- applescript - 在 web 表单中输入值并使用 applescript 按下返回键
- angular - Angular:ngModel 错误,因为我使用的是数组
- c++ - 调用接受 unique_ptr 对象的函数
- python - Selenium 不获取 url(3 行 python)
- html - Laravel 表单动作为空
- amazon-web-services - 查看 Amazon S3 上当前的请求数和数据传输数
- php - 在搜索功能中使用 PHP str_replace 不会返回所需的结果
- android - 无法从 Android 10 上的 BroadcastReceiver 开始活动