如何解除绑定或关闭所有jquery函数?

时间:2013-09-03 13:30:46

标签: javascript jquery ajax pushstate

我构建了一个具有推送状态的应用。一切都很好。但是在某些情况下,我的jquery函数会多次触发。那是因为当我调用push状态时,我为每个调用的页面绑定特定的js文件。这意味着当我在我的页面中浏览时,相同的js函数被绑定多次到html。

提示:我在我的jquery函数中使用documen.on,因为我需要通过Ajax将函数绑定到动态打印的HTML。

我尝试在打印前使用off状态,但没有成功!

这是我的代码:

var requests = [];

        function replacePage(url) {

            var loading = '<div class="push-load"></div>'
            $('.content').fadeOut(200);
            $('.container').append(loading);

            $.each( requests, function( i, v ){
                v.abort();
            });

            requests.push( $.ajax({                     
                    type: "GET",
                    url: url,
                    dataType: "html",
                    success: function(data){            

                        var dom = $(data);
                        //var title = dom.filter('title').text();
                        var html = dom.find('.content').html();
                        //alert(html);
                        //alert("OK");
                        //$('title').text(title);
                        $('a').off();
                        $('.push-load').remove();                       
                        $('.content').html(html).fadeIn(200);
                        //console.log(data);

                        $('.page-loader').hide();
                        $('.load-a').fadeIn(300);                       
                    }
                })
            );
        }

        $(window).bind('popstate', function(){
            replacePage(location.pathname);
        }); 

提前致谢!

2 个答案:

答案 0 :(得分:0)

使用空白代码简单绑定新函数

$( "#id" ).bind( "click", function() {
//blank
});

使用

 $('#id').unbind();

答案 1 :(得分:0)

试试这个,

 var requests = [];

   function replacePage(url) {
       var obj = $(this);
       obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
       var loading = '<div class="push-load"></div>';
        $('.content').fadeOut(200);
        $('.container').append(loading);
       $.each(requests, function (i, v) {
           v.abort();
       });
       requests.push(
       $.ajax({
           type: "GET",
           url: url,
           dataType: "html",
           success: function (data) {
               var dom = $(data);
                    //var title = dom.filter('title').text();
                    var html = dom.find('.content').html();
                    //alert(html);
                    //alert("OK");
                    //$('title').text(title);
                obj.bind("click", replacePage); // binding after successfulurl ajax request
                 $('.push-load').remove();                       
                    $('.content').html(html).fadeIn(200);
                    //console.log(data);

                    $('.page-loader').hide();
                    $('.load-a').fadeIn(300);    
            }
       }));
   }

希望这有帮助,谢谢