防止jQuery .scroll函数在执行.scroll函数内部时运行

时间:2014-07-17 12:02:32

标签: javascript jquery javascript-events

我想阻止jQuery .scroll函数在执行.scroll函数内部运行时运行。 原因是它可能会运行两次并给我带来麻烦。

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 50) {


// do stuff

} 

我试过了:

var carRun = true;   
     if (canRun==true){
            $(window).scroll(function() {
            if($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
            canRun=false;

            // do stuff

            canRun=true;
    } 
}

并没有解决问题。

编辑:

这些是我尝试过的东西的测试,但对我来说不起作用: 一:

     var canRun = true;
$(window).scroll(function() {
    if (canRun == true){
   if( $(window).scrollTop() + $(window).height() > $(document).height() - 50 ) {
            canRun = false; 

            // Are there more posts to load?
            if (pageNum <= max) {
                console.log(max);
                // Show that we're working.
                $('#loadmoreLink').text('Loading posts...');

                $('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post',
                    function() {
                        // Update page number and nextLink.
                        console.log("The number of the next page to load: " + pageNum);
                        pageNum++;
                        console.log("The number of the next page to load after increment: " + pageNum);
                        nextLink = 'http://www.example.com.br/page/' + pageNum + '/';
                        console.log("The link of the next page: " + nextLink);

                        // Add a new placeholder, for when user clicks again.
                        $('#pbd-alp-load-posts')
                            .before('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>');
                        console.log("--------END AJAX-------------");
                        // Update the button message.
                        if(pageNum <= max) {
                            $('#pbd-alp-load-posts a').text('Load More Posts');
                        } else {
                            $('#pbd-alp-load-posts a').text('No more posts to load.');
                        }
                    }
                );
            }
        canRun = true;
        }
    }
    });

No.2:

     var canRun = true;
$(window).scroll(function() {
   if( ($(window).scrollTop() + $(window).height() > $(document).height() - 50 ) && (canRun == true ) ) {
            canRun = false; 

            // Are there more posts to load?
            if (pageNum <= max) {
                console.log(max);
                // Show that we're working.
                $('#loadmoreLink').text('Loading posts...');

                $('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post',
                    function() {
                        // Update page number and nextLink.
                        console.log("The number of the next page to load: " + pageNum);
                        pageNum++;
                        console.log("The number of the next page to load after increment: " + pageNum);
                        nextLink = 'http://www.example.com.br/page/' + pageNum + '/';
                        console.log("The link of the next page: " + nextLink);

                        // Add a new placeholder, for when user clicks again.
                        $('#pbd-alp-load-posts')
                            .before('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>');
                        console.log("--------END AJAX-------------");
                        // Update the button message.
                        if(pageNum <= max) {
                            $('#pbd-alp-load-posts a').text('Load More Posts');
                        } else {
                            $('#pbd-alp-load-posts a').text('No more posts to load.');
                        }
                    }
                );
            }
        canRun = true;
        }
    });

这个有用:

jQuery(document).ready(function($) {

    // The number of the next page to load (/page/x/).
    var pageNum = parseInt(pbd_alp.startPage);
    // The maximum number of pages the current query can return.
    var max = parseInt(pbd_alp.maxPages);   
    // The link of the next page of posts.
    var nextLink = pbd_alp.nextLink;
    //what page am I on? 
    var whatPage = pbd_alp.theTitle;
    //console.log(whatPage);

    /**
     * Replace the traditional navigation with our own,
     * but only if there is at least one page of new posts to load.
     */
    if(pageNum <= max) {
        // Insert the "More Posts" link.
        $('#content').append('<div class="pbd-alp-placeholder-'+ pageNum +'"  ></div>')
        .append('<p id="pbd-alp-load-posts"><a href="javaScript:void(0);" id="loadmoreLink" onclick="_gaq.push([\'_trackEvent\', \'Click\', \'LoadMore\', \''+ whatPage +'\']);">Load More Posts</a></p>');

        // Remove the traditional navigation.
        $('.navigation').remove();
    }


    /**
     * Load new posts when the link is clicked.
     */

    var timerId = false;
    var canRun = true;

    $(window).bind('scroll', function() {

        if(canRun == true){
           if( $(window).scrollTop() + $(window).height() > $(document).height() - 50 ) {
                    canRun = false; 

                    // Are there more posts to load?
                    if (pageNum <= max) {
                        console.log(max);
                        // Show that we're working.
                        $('#loadmoreLink').text('Loading posts...');

                        console.log("start loading things from ");
                        $('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post', function() {
                                console.log("Im in da callback, loading has finished");
                                // Update page number and nextLink.

                            //the target of load is '.pbd-alp-placeholder-'+ pageNum
                            //pageNum must'nt be changed before loading.
                                console.log("The number of the next page to load: " + pageNum);
                                pageNum++;
                                console.log("The number of the next page to load after increment: " + pageNum);
                                nextLink = 'http://www.example.com.br/page/' + pageNum + '/';
                                console.log("The link of the next page: " + nextLink);


                                // Add a new placeholder, for when user clicks again.
                                $('#pbd-alp-load-posts').before('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>');

                                // Update the button message.
                                if(pageNum <= max) {
                                    $('#pbd-alp-load-posts a').text('Load More Posts');
                                } else {
                                    $('#pbd-alp-load-posts a').text('No more posts to load.');
                                }

                                //and now that I have finished, we can load more stuff
                                canRun = true;
                        });
                    }
            }
        }
    });
});

4 个答案:

答案 0 :(得分:0)

如果语句进入函数内部。此外,您需要将变量定义为canRun而不是carRun。否则,您将无法设置具有全局范围的变量。

var canRun = true;   

$(window).scroll(function() {
    if (canRun==true){
        if($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
            canRun=false;

            // do stuff

            canRun=true;
        } 
     }
}

另外,请考虑最常见的答案:jQuery - how to treat scroll as single event?每200ms只允许一次函数调用。

答案 1 :(得分:0)

您可以设置window.scroll_working等窗口属性,在if循环和if功能之前设置为true。逻辑:

$(window).scroll(callback)

function callback() {
    if(window.working) return;

    if($(window).scrollTop() + $(window).height() > $(document).height() - 50) {

    window.working = true;
    // do your stuff
    } 
    window.working = false
}

working demo

答案 2 :(得分:0)

这将做你想做的事:http://jsfiddle.net/CQffC/2/

它只允许每5秒运行一次滚动代码,但它会在允许的情况下立即执行。当然,您可以根据自己的喜好对其进行修改。

$(document).ready(function () {
    var timerId = false;

    $(window).bind('scroll', function() {
        if (timerId==false) {
            console.log('here');

            /* Do Stuff Here */

            timerId = setTimeout(function(){
                    timerId = false;
            }, 5000)
        }
    });
});

答案 3 :(得分:0)

正如我在评论中推测的那样,问题(除了最初位于错误位置的if语句之外)是你正在开始一个异步过程(在这种情况下是一个使用jQuery的{{1}的AJAX请求在.load()事件处理程序中。这意味着您当前的执行顺序基本上是这样的:

  1. scroll设为false
  2. 启动AJAX请求
  3. canRun设为true
  4. 收到对AJAX请求的回复并使用它做一些事情
  5. 您显然希望执行顺序为:

    1. canRun设为false
    2. 启动AJAX请求
    3. 收到对AJAX请求的回复并使用它做一些事情
    4. canRun设为true
    5. 你是怎么做到的?

      在当前AJAX请求的回调中将canRun设置为true(将函数作为第二个参数传递给canRun),而不是在调用.load()之后立即设置。