我正在和简单的javascript聊天:
<script>
function chatClick(messages_other_user) {
$('#chatBox').remove();
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}
</script>
这个函数在几个链接中被调用,变量"messages_other_user“也在改变。
在"chat.php“文件中,我获得了变量"ou”,并且我有一个脚本可以写入控制台:
if (isset($_GET['ou'])) { $otherUserChat = $_GET['ou']; } else $otherUserChat = 0; // get $otherUserChat
<script>
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
console.log("<?= $otherUserChat ?>");
}, 2000);
$.ajaxSetup({ cache: false });
});
</script>
但是javascript行并没有完全去掉chat.php文件中的.remove。当我单击一个链接来调用javascript chatClick函数时,它工作得很好。但是,当我单击另一个链接,该链接使用"messages_other_user“的不同变量调用chatClick时,旧的链接继续触发新的链接。
我如何完全销毁旧的javascript,这样它就不再运行了?
发布于 2020-07-09 16:37:38
我找到了解决方案--我被这个问题的真正罪魁祸首搞错了。
我认为console.log会产生与我真正做的事情相同的结果--为了简单起见,我只是选择在代码中用console.log替换。所以我想我已经认识到这是一件愚蠢的事情。
文档就绪脚本中的chat.php文件中实际发生的情况如下:
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000);
});
我发现我并不需要准备好使用这个文档,所以我直接在我的脚本中这样做:
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000); // CHECK FOR UNREAD: 1000 equals 1 second
$.ajaxSetup({ cache: false });
为了关闭聊天窗口,我现在触发此函数:
function closeChat() {
clearInterval(chatUpdateVar);
$('#chatBox').remove();
}
在调用上述脚本的文件(chat.php)中,我检查函数closeChat是否存在-如果存在,则运行它。这是对chat.php调用的一部分:
function chatClick(messages_other_user) {
if (typeof closeChat === "function") {
closeChat();
}
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}
https://stackoverflow.com/questions/62809134
复制相似问题