Ajax加载和以前的活动脚本

时间:2014-05-05 12:53:05

标签: javascript jquery ajax

我调用加载函数将内容加载到我的#content div中。 所有工作,但我的问题是这个div有时包含需要脚本运行的内容。 (这里是MIXITUP)

现在,我调用(回调函数)加载后运行mixitup的函数(ajax)但是当我加载内容多次时,mixitup似乎有点丢失,过滤器btn失去了活动类。

这是我的文件AJAX.php的代码:

$(function() {
    // historique
    $(window).bind('popstate', function() {
        console.log( "popstate event" );

        var url = window.location;
        var hash = url.href.substring(url.href.lastIndexOf('/') + 1);

        $('#content').load( url + ' #content');
    });

    // hide loading
    $('#loading').hide();

    // menu action link click
    $('.menu a').click(function(e) {
        e.preventDefault();

        $('#loading').slideDown(500);

        $("html, body").animate({ scrollTop: $('#loading').offset().top }, 20);

        $('.menu li').removeClass('active');
        $(this).parent().addClass('active');

        var lien = $(this).attr('href');

        $('#content').fadeOut(500, function() {
            $('#content').load( lien + ' #content> *', function () {    
                $('#content').fadeIn(500, function() {
                    $('#loading').slideUp();

                    history.pushState(null, null, lien);
                });
            }); 
        });
    });
});

这是my.js

function mixitNow() {
    $('.mixit').mixItUp({
        load: {
            filter: 'all' 
        },
        controls: {
            toggleFilterButtons: false,
            toggleLogic: 'or',
            live: true,
        },
        callbacks: {
            onMixEnd: function(state) {
                $("body").getNiceScroll().resize();
            }
        }
    });

    $( "a.toggle" ).click(function() {
        $(".linkto a.toggle[data-target="+$(this).attr('data-target')+"]").toggleClass( "active" );
        // Trigger the NiceScroll to resize
        $("body").getNiceScroll().resize();
    });

    $('.navmenu').niceScroll({cursorcolor: "#84dbff", cursorborder: "none", cursorwidth: "4px", cursorborderradius: "0", scrollspeed: "100"});
    $("body").niceScroll({cursorcolor: "#22ABDE", cursorborder: "1px solid #fff", cursorborderradius: "0", scrollspeed: "100"});
};

$(document).ready(function() {
    mixitNow(); //works
    console.log( "doc ready call 2 mixit" );
});

$(document).ajaxSuccess(function() {
    console.log( "ajaxSuccess" );
    mixitNow(); //works
});

2 个答案:

答案 0 :(得分:0)

而不是.load()你可以使用$ .ajax并使用成功处理程序

$.ajax({
    url: url,
    type: 'GET',
    success:function(response){
        // check response and 
        if(xyz){
            mixItUp()
        }else {
            // else no mixin
        }
    }

})

答案 1 :(得分:0)

在新的ajax调用之前,必须从内存中删除MixItUp的实例,否则将阻止对同一元素的进一步实例化。在进行ajax调用之前调用它。

try {
        $('.mixit').mixItUp('destroy');
    }catch(x) {}