首页 > 解决方案 > 通过 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......");
});

当然,此代码无法正常工作,因为它在单击一个按钮时会切换所有按钮。但我想知道只切换被点击的按钮的正确方法是什么?

感谢您的任何建议!

标签: jquerynode.jssocket.io

解决方案


You can use the this keyword to select the clicked element, eg.

$("button").click(function(){
  socket.emit("click button");
  $(this).toggleClass("blue");
  return false;
});

推荐阅读