【发布时间】:2016-06-19 12:41:37
【问题描述】:
我一直在试用 socket.io,显然是从他们的聊天应用开始的。他们这边的客户端代码看起来像这样:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="" id = "frm">
<input id="m" autocomplete="off" /><button id='b'>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
现在,我的问题是,如果我尝试更改 socket.on 块内的回调函数内的代码,如下所示:
document.getElementById('messages').innerHTML += '<li>' + msg + '</li>';
li 元素出现半秒钟,然后 innerHTML 重置,如果我尝试在回调中编辑 DOM 的任何其他部分,也会发生同样的事情?
我不使用 Jquery,但常识让我假设
$('#messages').append($('<li>').text(msg))
;基本上相当于以我上面写的方式修改innerHTML。我究竟做错了什么 ? socket.io 是否以只能在其回调中使用 Jquery 的方式制作? (我在服务器浏览器中试过这个)。
【问题讨论】:
-
对此的答案:“socket.io 是否以只能在其回调中使用 Jquery 的方式制作?”没有。您的问题与 Socket.io 无关
标签: javascript jquery html socket.io socket.io-1.0