0

我在 app.js 中有这段代码

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
static = require('node-static');
var fileServer = new static.Server('./');
app.listen(8080);
function handler (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    });
}
io.set('log level', 1);
io.sockets.on('connection', function (socket) {
     socket.on('click', function () {
            socket.broadcast.emit('moving');
        });

});

索引.html

<script>
    var url = window.location.hostname;
    var socket = io.connect(url);
     socket.on('moving', function () {
        $("body").append('<div class="text">tex</div>');
     });
</script>

我想写简单的文本(div),但它不起作用..哪里有问题?

4

1 回答 1

1

默认情况下, socket.io 不会帮助观察click事件。编辑您的客户端代码,如下所示:

<script>
    var url = window.location.hostname;
    var socket = io.connect(url);
    socket.on('moving', function () {
        $("body").append('<div class="text">tex</div>');
    });
    // manually emit the event, or bind `click` inside dom
    // and call socket.emit('click') inside onClick()
    socket.emit('click');
</script>
于 2013-03-05T17:53:30.833 回答