0

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

有没有办法让 jQuery 触发一个类似于load告诉我数据的 iframe/图像/视频何时完成加载的事件?之前还是之后append()

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

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

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

我试图通过将load事件附加到window对象load()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");
    });
});

这个问题与

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

4

2 回答 2

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);
});
于 2012-10-11T16:22:20.727 回答
0

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

于 2012-10-31T12:45:52.043 回答