我正在建立一个套接字聊天程序,每当有人加入聊天室时,一个显示用户数量的徽章就会增加。 下面的代码是将新用户的名称添加到用户列表的功能。新名称将添加为具有id =" elementInPeople的div。我的问题是徽章只显示1,即使多个用户已进入聊天。有关如何解决此问题的任何建议吗?
socket.on("update-people", function(people){
$("#people").empty();
$.each(people, function(clientid, name) {
$people.append('<div id="elementInPeople">' + name + '</div>');
var np = $("#elementInPeople").length;
$("#numberOfPeopleOnline").text(np);
});
});
服务器端:
socket.on("connection", function(client) {
client.on("join", function(name){
console.log("Someone joined the chat");
people[client.id] = name;
client.emit("updateToSelf", "You have connected to the server. Join or create room to chat");
socket.sockets.emit("update-people", people);
client.broadcast.emit('updateToOthers', name + " has joined the server.");
});
答案 0 :(得分:1)
无需在dom中搜索数据中已有的数量。
people
似乎是一个对象,因此Object.keys(people).length
可以为您提供计数
socket.on("update-people", function(people){
$(".people").empty();
$.each(people, function(clientid, name) {
$people.append('<div class="elementInPeople">' + name + '</div>');
});
var np = Object.keys(people).length;
$("#numberOfPeopleOnline").text(np);
});
答案 1 :(得分:0)
var np = $("#elementInPeople").length;
这是你的问题。对于数组中的每个元素,您必须添加一些公共类名。像:
$people.append('<div id="elementInPeople" class="countable_people">' + name + '</div>');
然后你可以找到这样的人数:
var np = $(".countable_people").length;
$("#numberOfPeopleOnline").text(np);
答案 2 :(得分:0)
试试这个!
socket.on("update-people", function(people){
$(".people").empty();
$.each(people, function(clientid, name) {
$people.append('<div class="elementInPeople">' + name + '</div>');
});
var np = $(".elementInPeople").length;
$("#numberOfPeopleOnline").text(np);
});
&#13;