【问题标题】:How to re-bind jQuery window scroll again after unbinding it?取消绑定后如何重新绑定jQuery窗口滚动?
【发布时间】:2015-04-16 08:41:19
【问题描述】:

在使用unbind() 阻止 div 自我复制 - (#mystat-1) 之后,我需要再次将 bind()scroll() 重新转换为 $(window)。我试过$(window).bind('scroll'); 但它不起作用。谢谢!

$(window).scroll(function() {
    if ($("#moreSection").visible(true)) {
        doActionAndStopScript();
    }
});

function doActionAndStopScript() {
    $('#myStat-1').circliful() // now it will fire once
    $(window).unbind('scroll');
}

【问题讨论】:

    标签: jquery scroll bind unbind


    【解决方案1】:

    对于这种情况,我建议您使用event.namespace。我还建议您使用$.fn.on()$.fn.off()

    代码是不言自明的。

    //Declare a event hanlder
    function scrollHandler(){
        if ($("#moreSection").visible(true)){
            doActionAndStopScript();
    
            //Bind event
            $(window).on('scroll.test', scrollHandler);
        }
    }
    
    function doActionAndStopScript(){
        // now it will fire once
        $('#myStat-1').circliful();
    
        //Unbind it
        $(window).off('scroll.test');
    }
    
    //Bind event
    $(window).on('scroll.test', scrollHandler);
    

    【讨论】:

      【解决方案2】:

      您可以在doActionAndStopScript 函数中再次绑定event

      function scrollHandler() {
             if ($("#moreSection").visible(true)){
                  doActionAndStopScript();
             }
      }
      
      $(window).scroll(scrollHandler);
      
      function doActionAndStopScript(){
           $('#myStat-1').circliful();
           $(window).unbind('scroll');
       }
      

      现在您可以使用$(window).bind('scroll', scrollHandler);再次绑定事件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多