成功的ajax调用后,jQuery重新绑定$(window).scroll()

时间:2012-02-12 13:11:07

标签: javascript jquery ajax

我已经制作了这个无限滚动的脚本,但是在我取消绑定之后我无法重新绑定窗口滚动。这是脚本:

$(function(){
    $(window).scroll(function(){
        var mostOfTheWayDown = ($(document).height() - $(window).height()) * 2 / 3;
        if ($(window).scrollTop() >= mostOfTheWayDown) {
            $(window).unbind('scroll');
            $.ajax({
                url: 'loadmore',
                data: {lastrank: lastrank},
                dataType: 'json',
                type: 'POST',
                success: function(json){
                    //some work here
                    $(window).bind('scroll');
                }
            });
        }
    });
});​

如果成功调用ajax后如何重新绑定窗口滚动?

3 个答案:

答案 0 :(得分:7)

$(function(){
    var scrollFunction = function(){
        var mostOfTheWayDown = ($(document).height() - $(window).height()) * 2 / 3;
        if ($(window).scrollTop() >= mostOfTheWayDown) {
            $(window).unbind("scroll");
            $.ajax({
                url: "loadmore",
                data: {lastrank: lastrank},
                dataType: "json",
                type: "POST",
                success: function(json){
                    //some work here

                    $(window).scroll(scrollFunction);
                }
            });
        }
    };
    $(window).scroll(scrollFunction);
});​

答案 1 :(得分:0)

您需要将回调函数传递给.bind()方法,该方法执行滚动事件触发时您想要发生的任何事情。您还需要先调用unbind('scroll'),这样每次用户滚动时都不会执行两个函数。

答案 2 :(得分:-1)

与其他答案类似,但改为使用绑定。

$(function(){

  function scrollStuff() {

    var mostOfTheWayDown = ($(document).height() - $(window).height()) * 2 / 3;
    if ($(window).scrollTop() >= mostOfTheWayDown)
    {
      $(window).unbind('scroll');
      $.ajax({
        url: 'loadmore',
        data: {lastrank: lastrank},
        dataType: 'json',
        type: 'POST',
        success: function(json){
          //some work here
          $(window).bind('scroll', scrollStuff);
        }
      });
    }
  }

  $(window).bind('scroll', scrollStuff);
});