脚本在AJAX加载的DIV中不起作用,仅加载了html吗?

问题描述 投票:0回答:1

我的JavaScript在ajax响应后无法正常工作,我知道我必须使用$('.ajax-link').on('click', 'a', function (e){功能,但是当我使用它时,我的e.preventDefault();无法正常工作(意味着整个页面正在加载而不是ajax调用),如果我正在使用$('a.ajax-link').click(function (e) {,那么ajax可以正常运行,但是ajax响应页面的所有脚本均无法正常工作在ajax响应之后。我正在使用jquery 1.10。下面是我的整个代码:

$('a.ajax-link').click(function (e) {
        NProgress.start();
        if (msie) e.which = 1;
        if (e.which != 1 || !$('#is-ajax').prop('checked') || $(this).parent().hasClass('active')) return;
        e.preventDefault();
        $('.sidebar-nav').removeClass('active');
        $('.navbar-toggle').removeClass('active');
        $('#loading').remove();
        $('#dvLoading').show();
        var $clink = $(this);
        History.pushState(null, null, $clink.attr('href'));
        $('ul li.active').removeClass('active');
        $clink.parent('li').addClass('active');
    });

    History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
        var State = History.getState(); // Note: We are using History.getState() instead of event.state   



    $.ajax({
        url: State.url,
        success: function (msg) {
           $('#dvLoading').fadeOut(10);
            NProgress.inc();
            $('.main-sec').html($(msg).find('.main-sec').html());
             NProgress.inc();
            setTimeout(function() { NProgress.done(); $('.fade').removeClass('out'); }, 100);
            $('#loading').remove();
            $('.main-sec').fadeIn();
            var newTitle = $(msg).filter('title').text();
            $('title').text(newTitle);
            docReady();
        }
    });
});
php jquery arrays ajax jquery-events
1个回答
0
投票

您可以手动将scripts标记附加到您的文档中:

$.ajax({
    url: State.url,
    success: function (msg) {
      var scripts = $("<div>").html(msg).find( "script");
      scripts.each(function(){
          $('body').append($(this)[0]);
        }
    }
});

或您可以使用AMD模式,请查看requirejs:http://requirejs.org/

© www.soinside.com 2019 - 2024. All rights reserved.