动态加载HTML/Javascript

Le_*_*eur 2 html javascript jquery

我有一个index.html页面,我想使用jQuery动态地将另一个页面的内容加载到index.html.我使用$ .load()函数来执行此操作:

$('#dynamic_content').load('another.html #toLoad')
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我还需要加载使用another.html的javascript文件,所以我这样做:

$('#dynamic_content').load('another.html #toLoad');
$.getScript('js/another.js');
Run Code Online (Sandbox Code Playgroud)

问题是'another.js'的js代码有时不会'应用'到html页面(可能它比html页面更早加载)another.js的内容:

$(document).ready(function {} {

   $('#cancelButton').click(function() {
       //do something 

});

});
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 10

使用成功回调:

$('#dynamic_content').load('another.html #toLoad', function() {
    $.getScript('js/another.js');
});
Run Code Online (Sandbox Code Playgroud)

这样,如果another.js从中操纵动态加载的内容,another.html将保证该内容已经被注入到当前DOM树中.