【发布时间】:2015-04-27 10:17:19
【问题描述】:
我现在正在做一个 PHP 聊天。 当用户登录时,他会自动向所有人发送“已登录”消息,当他注销时,他会自动向所有人(当然除了他)发送“已注销”消息。 当所有用户登出时,所有消息都会被自动删除。
我现在正在开发一个功能,它可以告诉您,无论您是否独自在聊天室中。 我想用 JavaScript 解决这个问题。我现在使用的脚本会计算“登录”和“退出”一词在聊天记录中出现的频率(是的,不是最终的解决方案,但对我的使用来说绝对足够了)
代码如下:
function countverlassen(){
var temp = document.body.innerText;
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var countverlassen = (temp.match(/verlassen/g) || []).length +1;
console.log(countverlassen);
}
function countbetreten(){
var temp = document.body.innerText;
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var countbetreten = (temp.match(/betreten/g) || []).length;
console.log(countbetreten);
if (countbetreten >= 2 && countbetreten != countverlassen){
$('.alleine').hide();
}
else if (countverlassen >= 2 && countbetreten == countverlassen) {
$('.alleine').show();
}
}
类“alleine”只包含文本“你现在一个人在这里”。 当另一个用户登录时,它应该被隐藏,当除您之外的所有其他用户退出时,它应该再次显示。 隐藏课程效果很好,但当其他人退出时它不会再次出现。
您可以在这里看到它的实际效果:http://team3.digital-cultures.net/index.php# 只需选择一个名称并从下拉列表中选择一个起点/目的地。
我做错了什么? 谢谢!
编辑:出于测试目的,您只需在聊天中输入“betreten”(“用德语登录”)和“verlassen”(“用德语注销”),无需使用多个帐户登录 :)
【问题讨论】:
-
您需要继续使用 ajax 进行轮询,以检查登录的用户数并据此显示
-
这可能会导致轮询或 websocket 运行。
-
我基本上是这样做的 - 每次发送新消息时,函数都会被加载并再次计数(您可以在控制台日志中看到它)
标签: javascript show-hide