Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

javascript - Unsure on why .load() complete event isn't working

I'm unsure on why this isn't working:

$(document).ready(function() {
      setInterval(RefreshDiv, 2000);
    })

    function RefreshDiv(){
      $('#box').load('messages.php #box', function() {
        $('#box').on('load', function() {
          $('#box').scroll(0, 50);
        });
      });
    }

The tags are correct and the .load() part works every two seconds but I don't understand why my complete event to scroll down 50px isn't working?

I've also tried another method to scroll:

var log = document.querySelector('#box');
log.scrollTop = log.scrollHeight - log.clientHeight;

but this also doesn't execute on load

Edit #1

jQuery($ => {
      setInterval(RefreshDiv, 2000);
    })

    function RefreshDiv() {
      $('#box').load('messages.php #box', () => {
        $('#box').scrollTop(50);
      });
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The load event only fires on certain elements such as img and the window object. As such I presume #box is not one of them.

You don't actually need the load event handler anyway as the callback itself runs when the load() method completes its request. Try this:

jQuery($ => {
  setInterval(RefreshDiv, 2000);
})

function RefreshDiv() {
  $('#box').load('messages.php #box', () => {
    $('#box').scrollTop(5000);
  });
}

It's also worth noting that sending AJAX requests every 2 seconds is not ideal, as it will not scale as you have more concurrent visitors to your site, and can lead to server performance problems. There's likely to be a much better alternative, depending on what it is you're doing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...