jQuery.find()偶尔找不到

jQuery .find() fails to find occasionally

本文关键字:偶尔 找不到 find jQuery      更新时间:2023-09-26

我正试图通过将网页的HTML加载到iframe中来将其解析为DOM,然后在DOM上进行一些搜索。这是代码

function f(callback) {
    var tmp = document.createElement('iframe');
    $(tmp).hide();
    $(tmp).insertAfter($('foo'));
    $(tmp).attr('src', url);
    $(tmp).load(function() {
        var bdy = tmp.contentDocument.body;
        callback(bdy);
        $(tmp).remove();
    });
}

在回调函数中,如果我做了如下

function callback(bdy) {
    alert($(bdy).find('bar').length);
}

有时它会给出正确的值,但有时它会给我0。然而,如果我做以下操作,它会起作用

var tmp = document.createElement('iframe');
$(tmp).hide();
$(tmp).insertAfter($('foo'));
$(tmp).attr('src', url);
$(tmp).load(function(tmp) {
    setTimeout(function() {
        var bdy = tmp.contentDocument.body;
        callback(bdy);
        $(tmp).remove();
    }, '100');
});

由于setTimeout()取决于客户端,我想知道是否有更好的方法来实现同样的目标。谢谢

看看这个问题,以及它的许多答案和相关问题。


更新;以下是一些等待加载#bar的代码:

function f(callback) {
    var tmp = document.createElement('iframe'),
        $tmp = $(tmp);
    $tmp.hide()
        .insertAfter($('foo'))
        .attr('src', url);
    $tmp.load(function() {
        var bdy = tmp.contentDocument.body,
            $bdy = $(bdy); // small optimization
        var waitForBar = function() {
            if($bdy.find('#bar').length > 0) {
                callback(bdy);
                $tmp.remove();
            } else
                setTimeout(waitForBar, 50);
        };
        waitForBar();
    });
}