javascript - 动态加载 HTML/Javascript

标签 javascript jquery html

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

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

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

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

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

$(document).ready(function {} {

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

});

});

最佳答案

使用成功回调:

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

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

关于javascript - 动态加载 HTML/Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6397727/

相关文章:

javascript - 如何从数组中返回匹配项之前的 2 个元素?

jquery - 将图像旋转 360 度

javascript - 电子应用程序中的 jQtree 定位问题

javascript - 将其他选项向下推的垂直下拉菜单?

javascript - 如何在ajax调用中使用flask url_for?

javascript - 暂时禁用事件监听器并稍后重新绑定(bind)

javascript - AngularJS 和使用哈希 URL 的 js/css 库

html - css 转换完成后延迟隐藏元素

javascript - "string.match()"不是函数?

jquery - 如何选择 id 以 "menu"或 "submenu"开头的所有 imgs?