1

我正在尝试为我的聊天框创建通知,当有人向您发送新消息时,可以在“谈话”标题旁边看到。我已经尝试了多种从未奏效的东西。

一只忙碌的猫 http://goawaymom.com/damit.png

这是我的代码

$(document).ready(function(){
  //If user submits the form
  $("#submitmsg").click(function(){ 
    var clientmsg = $("#usermsg").val();
    $.post("post.php", {text: clientmsg});              
    $("#usermsg").attr("value", "");
    return false;
  });

  //Load the file containing the chat log
  function loadLog(){       
    $.ajax({
      url: "log.html",
      cache: false,
      success: function(html){     
        var chatbox= $("#chatbox");
        var atBottom = (chatbox[0].scrollHeight - chatbox.scrollTop() == chatbox.outerHeight());
        chatbox.html(html);

        if (atBottom )
          chatbox.animate({ scrollTop: 99999 }, 'normal');
      }
    });
  }
  setInterval (loadLog, 2500);  //Reload file every 2.5 seconds

  //If user wants to end session
  $("#exit").click(function(){
    var exit = confirm("Are you sure you want to end the session?");
    if(exit==true){window.location = 'index.php?logout=true';}
  });
});

有没有人知道我会怎么做。到目前为止,我尝试过的一切都失败了。我尝试使用不起作用的设置间隔函数。

4

2 回答 2

0

那么,如果我理解正确,提交消息会将其附加到 log.html 的末尾?我认为这对你想做的事情不起作用。您需要有一个服务来跟踪新帖子,以便您可以检查更新,而不仅仅是重新加载 div 的 innerHTML。

一旦你有了它,你就可以计算自从聊天获得焦点以来你加载了多少新消息,并在每次聊天获得焦点时将其重置为 0。

您可以使用 document.title 更新标题。因此,每当您需要更新计数时,您都可以

document.title = 'my normal title (' + newCount + ')';

简而言之,这不是你可以用 javascript 解决的问题,你需要重新设计你的应用程序。

于 2012-09-19T18:54:11.063 回答
0

你的问题有点不完整/不清楚。当您说“每当有人向您发送新消息时”时,您的意思是仅在出现新消息时(对您来说不是必需的,而是整个聊天室都需要)。

假设是这种情况,那么每当有人输入某些内容时,这个数字就会不断增加,这就引出了一个问题:你什么时候减少这个数字?

这是一段可以帮助您入门的代码。它不会减少通知号码,因为在您的问题中您没有说明该号码何时重置。

在最后$(document).ready添加以下行

// Load log and cache number of message on page when it first loaded
// Pass in a callback function to cache the message count. 
loadLog(function(){
  window.lastReadMessageCount = $('.msgln').length;
}); 

更新 loadLog 以接受回调:

function loadLog(callback){
  ...
  success: function(html){
    if (callback) callback();
    ...
  }
  ...
}          

现在您知道用户在页面加载时看到了多少条消息。现在,每当页面更新聊天时,我们都想更新新消息计数。

在您的loadLog(), 将以下行添加到末尾

newMessagesCount = $('.msgln').length - lastReadMessageCount;
document.title = newMessagesCount > 0 ? 'title (' newMessagesCount ')' : 'title';

就是这样!您现在需要做的就是明确何时更新 lastReadMessageCount。

于 2012-09-19T19:34:13.837 回答