如何在无限滚动中避免多个JavaScript函数调用

dir*_*ndd 3 javascript ajax jquery jsp javascript-events

我正在使用此Java Script函数来创建具有Infinite Scroll功能的JSP页面.

<script language="javascript" type="text/javascript">

var count = 0;

window.onload = loadSubPage;

$(window).scroll(function(){
    if  ($(window).scrollTop() == $(document).height() - $(window).height()){
    alert("load appLeadershipSubView function calling");
        loadSubPage();
    }
});

function loadSubPage()
{
    alert("load appLeadershipSubView called");
        $.ajax({
        cache: false,
        url: 'appLeadershipSubView.do?count=' + count,
        async : true,
        beforeSend: function(){
        },
        success: function(html){
            alert("success event");
            $('#mainDiv').append(html);
            count++;
        },
        complete: function(){
        }
    }
    );
} 

</script> 
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我正在调用loadSubPage函数将'appLeadershipSubView'页面中的html内容追加到'#mainDiv'中.并且还在页面Load事件中调用loadSubPage.

问题是,当我向下滚动时,它会对loadSubPage函数进行多次(有时是2次)调用,并将重复数据附加到div中.

由于我是JSP和Javascript的新手,我无法在这里找出问题所在.你能指点我这里的问题吗?

epa*_*llo 6

添加布尔值以确保没有活动请求.在提出请求之前,请检查它是否处于活动状态.

var isActive = false;
$(window).scroll(function(){
    if  (!isActive && $(window).scrollTop() == $(document).height() - $(window).height()){
    isActive = true;
Run Code Online (Sandbox Code Playgroud)

在回调中,将isActive设置为false

success: function(html){
    $('#mainDiv').append(html);
    isActive = false;
Run Code Online (Sandbox Code Playgroud)