且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用脚本标签进行jQuery .load()

更新时间:2023-12-05 07:50:40

文档明确提及这个:

但是,如果调用 .load()并在URL后面附加了选择器表达式,则会在更新DOM之前删除脚本,因此不会执行这些脚本.

If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

此线程似乎有答案-使用

This thread seems to have the answer - use get instead:

$('.navigation .nav li a').not('.nav-item-expandable > a').click(function(navActive){
    var href = $(this).attr('href');

    navActive.preventDefault();
    $.get('/' + href, function(html){
        var doc = $(html);
        $('.content').empty().append(doc.find('.content > *'));
        $('.breadcrumb').empty().append(doc.find('.navbar .breadcrumb > *'));
        $('#scripts').empty().append(doc.find('#scripts > *'));
        setTimeout(function(){ breadcrumb(); }, 200);
    });

    history.pushState('', '', href);
});

这也将更加高效,因为您只对新页面发出一个请求,而不是当前脚本发出的三个请求.

That will also be more efficient, since you're only making one request for the new page, rather than the three that your current script issues.