0

I'm working on a very simple jQuery based chat room (to be used in an introductory workshop). The current chats are displayed in a div set to 400px high and overflow auto.

jQuery's "load" function is used to retrieve HTML formatted chats from a database and place them into the div.

I've got some very simple code that ensures the chat div is scrolled to the bottom at all times. This code is in a function named scrollToBottom which is called using the completion callback feature in the load function:

The load statement is in a function called getChat, which is called when the page is ready and then once per second. Here's the relevant chunk of code:

$(function()
{
    getChat();
    setInterval("getChat();", 1000);
});


function getChat()
{
    $("#chatDiv").load("chat_server.php?get_chats=true", scrollToBottom() );
}


function scrollToBottom()
{
    var chatHeight = document.getElementById("chatDiv").scrollHeight;
    $("#chatDiv").scrollTop( chatHeight );
}

The Problem: The first time getChat is called, the div doesn't scroll to the bottom. In subsequent calls (via setInterval), the scrolling works fine.

Here's what I know / have done so far:

The callback IS being called the first time, however when I alerted the scrollHeight, it was "400" the first time and "441" subsequent times (i.e. what it should be when there is content bigger than the div size).

A scrollTop value of 400 for 441 high content should scroll to the bottom regardless, but when I put a hard value of 400 in scrollToBottom the problem persists. This makes me think the problem is related to CSS / scrolling rather than the load callback.

The chat div starts out empty, but changing it to include a nbsp or single letter didn't solve the problem. Making the div start out with enough hard-coded content to require scrolling DID solve the problem.

At this stage, it seems like the scrollbars need to be visible/active in order for scrollTop to work... but doesn't explain why it isn't working the first time - since the callback is meant to happen AFTER the content is loaded (and hence the scrollbar should be visible/active)...

Just to make it stranger still, it works fine if the callback function is an anonymous inline one...

$(function()
{
    getChat();
    setInterval("getChat();", 1000);
});


function getChat()
{
   $("#chatDiv").load("chat_server.php?get_chats=true", 
     function()
     {
        var chatHeight = document.getElementById("chatDiv").scrollHeight;
        $("#chatDiv").scrollTop( chatHeight );
     }
   );
}

This version works fine the first time and all subsequent times...

Can anyone shed any light on this situation? Thanks, Greg

4

1 回答 1

0

在 javascript 中,函数,无论是否匿名,都是一等的,这意味着它们可以作为参数传递。您无需使用匿名表单,也无需第一次调用该函数。只需将 scrollToBottom 作为参数传递即可加载:

$("#chatDiv").load("chat_server.php?get_chats=true", scrollToBottom);

同样,您可以简化 setInterval 调用:

setInterval(getChat, 1000);
于 2011-07-14T06:27:42.887 回答