javascript chat display messages
I am trying to implement a chat. I want to display the messages in a div. My model looks like:
<div id="chatcontentcontainer">
<div id="messageid">
<div class="sender">sender name</div>
<div class="messagebody">message text</div>
</div>
.....
.....
</div>
and my javascript looks like:
var messages = responseXML.getElementsByTagName('ChatMessage');
var chatContainer = document.getElementById('chatcontentcontainer');
for (var i = 0; i < messages.length; i++)
{
var msg = messages[i];
var x = document.createElement('div');
x.id = msg.children[0].textContent;
x.innerHTML = msg.children[1].textC开发者_如何学Goontent;
chatContainer.appendChild(x);
_lastMessageId = x.id;
}
This fills the div with messages without the sender info. For beginning there are just messages. How can I change this to check if a message was already displayed? Do you have any other suggestion for showing messages ... I am interesting in performance because this will be refresh every 5 second.
Is there any other way of selecting msg.children[0] something like msg.children['Id'] without impacting performances?
Each div that you add to the list needs to be annotated with information that exists in the data. For example, you could give the divs an id of child_id_{x} if each msg has an id.
Then, you could change your code to have an added check based on the id to make sure that element does not exist.
Make sense?
Associate a timestamp or sequence number with the messages. The XML returned from the server will have messages from time t0 to time t1. After displaying it on the page, store the last displayed message's timestamp in the browser somehow (in this case t1). When the next set of messages arrive, you just need to display those messages with id > t1.
implementation-of-running-commentary-on-any-ongoing-event is a similar problem for which I have given an end-to-end solution strategy there. You might find it helpful.
精彩评论