【问题标题】:creating new message notifications within <title></title> from a chat box通过聊天框在 <title></title> 中创建新消息通知
【发布时间】:2012-09-19 18:48:34
【问题描述】:

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

a busy cat 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';}
  });
});

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

【问题讨论】:

  • 你尝试了什么?你有什么问题?
  • 不重复,我已经尝试过他们在那篇文章中提到的内容。但他们似乎不明白我在问什么。我尝试使用设置间隔,但我在某处读到您不能为 通知使用设置间隔

标签: javascript jquery


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

    $(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。

    【讨论】: