onload方法拒绝使用javascript在我的页面上启动函数

onload方法拒绝使用javascript在我的页面上启动函数,javascript,jquery,Javascript,Jquery,您好,我已经使用html和JavaScript ajax构建了一个聊天系统 聊天中加载了很多信息,并会在页面上显示 因此,我尝试设计一种方法,使用下面的功能在聊天页面加载时向下滚动聊天信息 <script> function scrolldown() { var box = document.getElementById('chatmessagecontainer'); box.scrollTop = box.scrollHeight; } </scri

您好,我已经使用html和JavaScript ajax构建了一个聊天系统

聊天中加载了很多信息,并会在页面上显示

因此,我尝试设计一种方法,使用下面的功能在聊天页面加载时向下滚动聊天信息

<script>
  function scrolldown() {
    var box = document.getElementById('chatmessagecontainer');
    box.scrollTop = box.scrollHeight;
  }
</script>
但onload方法从不触发此函数

<body onload="scrolldown()">
然而,我注意到只要点击一个按钮,函数就会启动,如下所示

<input type="button" id="sub" onclick="scrolldown()" name="click" value="click" />
通过此id显示信息中的以下功能将消息加载到聊天室容器中

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


<script type="text/javascript">
  setInterval(loaddata, 1000);

  function loaddata() {
    var msgid = document.getElementById('msgid');

    if (msgid) {
      $.ajax({
        type: 'post',
        url: 'load.php',
        data: {
          msgid: msgid.value,
        },

        success: function(response) {
          // We get the element having id of display_info and put the response inside it
          $('#display_info').html(response);
        },
      });
    } else {
      $('#display_info').html('Please Enter Some Words');
    }
  }
  </script>

为什么onload方法不运行my函数?

尝试延迟函数的执行,例如,将其内容包装在setTimeout调用中2秒。我怀疑可能所有的页面元素都可以在DOM中使用,但尚未绘制


更新:虽然setTimeout是一种可能有效的方法,但它基本上是一种技巧。请注意,理想情况下,在尝试滚动之前,您应该观察元素并确保它可用和/或包含子元素。你可以用它。希望有帮助。

chatmessagecontainer元素是动态加载的吗?不是,其中的消息是动态加载的,我们需要更多信息。脚本标记位于头部、主体顶部/底部的什么位置?将消息添加到DOM后,首次加载页面时调用向下滚动时,消息是如何添加的,何时添加的?控制台中有任何错误吗?另一个div将消息传送到其中,chatmessagecontainer只是聊天版面的设计。请稍候,我将更新我的问题。我不知道为什么他的答案被标记下来,但他似乎理解我的问题,并根据我的方法为我提供了一个解决方案