最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery .on() and .off() don't work the way I'm using them - Stack Overflow

programmeradmin1浏览0评论

I have a page where I trigger an ajax load event when the user scrolls down to a certain portion of the page. I have the following ajax event handlers here:

$(document).ajaxStart(function() {
$('#loader').show();
$(window).off('scroll');
    }); 

$(document).ajaxComplete(function() {
    $('#loader').hide();
  $(window).on('scroll');
    });  

To prevent the ajax event from firing multiple times I turn off the scroll event handler at the beginning of an ajax call (I also wrote a delay function which will wait a few milliseconds before firing as well). My intention is to rebind the scroll after ajax is finished. I know these events are occurring because my #loader div is loading and unloading as designed. Unfortunately, the scroll never re-binds, it remains off and I cannot understand why. Hence, I load a single ajax page of new content then it stops working.

I have a page where I trigger an ajax load event when the user scrolls down to a certain portion of the page. I have the following ajax event handlers here:

$(document).ajaxStart(function() {
$('#loader').show();
$(window).off('scroll');
    }); 

$(document).ajaxComplete(function() {
    $('#loader').hide();
  $(window).on('scroll');
    });  

To prevent the ajax event from firing multiple times I turn off the scroll event handler at the beginning of an ajax call (I also wrote a delay function which will wait a few milliseconds before firing as well). My intention is to rebind the scroll after ajax is finished. I know these events are occurring because my #loader div is loading and unloading as designed. Unfortunately, the scroll never re-binds, it remains off and I cannot understand why. Hence, I load a single ajax page of new content then it stops working.

Share Improve this question edited Oct 5, 2012 at 21:49 Alnitak 340k72 gold badges418 silver badges501 bronze badges asked Oct 5, 2012 at 21:39 Joel Joel BinksJoel Joel Binks 1,6765 gold badges28 silver badges48 bronze badges 2
  • $(window).on('scroll'); what are you binding here? There is no actual handler. – Ilia G Commented Oct 5, 2012 at 21:42
  • 2 They work as designed. You aren't using them correctly. – Shmiddty Commented Oct 5, 2012 at 21:45
Add a ment  | 

1 Answer 1

Reset to default 6

The names "on" and "off" may be confusing; you can't use them to switch events on and off.

The off method removes the event handler pletely from the element. When you bind the event again, you have to specify the event handler:

$(window).on('scroll', handlerFunction);
发布评论

评论列表(0)

  1. 暂无评论