附加html代码时jQuery加载事件触发

时间:2012-10-11 16:10:43

标签: jquery ajax dom load

我正在使用jQuery的ajax函数$.get()从页面下载数据。然后我将该数据转换为带有$(data)的jQuery对象,允许它构造一个DOM树。然后,我使用append()

附加此数据

有没有办法让jQuery触发类似于load的事件,这会告诉我数据的iframes / images / videos何时加载?在append()之前或之后?

根据jQuery文档,load事件仅触发特定对象:

  

此事件可以发送到与URL关联的任何元素:图像,脚本,框架,iframe和窗口对象。

我可以循环遍历所有数据并将load侦听器附加到每个对象,然后计算有多少,并load处理程序计算已加载的数量(或已经加载了多少)已缓存),直到数字达到总数。但是,我正在寻找这种解决方案的替代方案。

我尝试通过loadwindowload()事件附加到on()对象,但这些事件仅在最初加载活动页面时触发一次。

这是我的代码:

$.get(url_string, function(data) {
    // Create DOM elements out of the downloaded html text 'data'
    // and take a subset of the DOM elements, where the id is #content
    var myContents = $(data).find("#content");

    // Insert DOM elements into the active page
    $("#destination").append(myContents);

    // Check when all images/iframes/video elements have loaded
    // Does not work
    $("#destination").load(function() {
        alert("new stuff loaded");
    });

    // Does not work either
    myContents.load(function() {
        alert("new stuff loaded");
    });
});

此问题与

相关联

但是这些提供的解决方案都是我上面提到的解决方案,在那里我必须计算有多少对象,然后检查何时达到总数。

2 个答案:

答案 0 :(得分:0)

您正在尝试在加载内容后分配加载事件。在附加内容之前定义它们。

试试这个,

$.get(url_string, function(data) {
    // Create DOM elements out of the downloaded html text 'data'
    // and take a subset of the DOM elements, where the id is #content
    var myContents = $(data).find("#content");

    // Check when all images/iframes/video elements have loaded
    $("#destination").load(function() {
        alert("new stuff loaded");
    });

    myContents.load(function() {
        alert("new stuff loaded");
    });

    // Insert DOM elements into the active page
    $("#destination").append(myContents);
});

答案 1 :(得分:0)

目前,最新版本的jQuery(1.8.2)不支持在附加HTML时触发DOM就绪事件。