2011-06-18 87 views
2

我有一个index.html页面,我想使用jQuery将另一个页面的内容加载到index.html。我使用$ .load()函数来做到这一点:动态加载HTML/Javascript

$('#dynamic_content').load('another.html #toLoad') 

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

$('#dynamic_content').load('another.html #toLoad'); 
$.getScript('js/another.js'); 

问题是“another.js”有时不“适用”于html页面的js代码(也许它比加载HTML页面更早) 内容another.js的:

$(document).ready(function {} { 

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

}); 

}); 
+0

您是否在加载html之前尝试加载脚本? –

回答

10

使用成功回调:

$('#dynamic_content').load('another.html #toLoad', function() { 
    $.getScript('js/another.js'); 
}); 

这样,如果another.jsanother.html操纵动态加载的内容将保证此内容已被注入到当前的DOM树。