javascript - IFrame 异步加载?如果不是为什么会出现这个错误?

标签 javascript jquery html iframe

编辑: 从测试来看,iframe 确实会异步加载(尽管不能完全确定)。我通过在 700 毫秒后调用该函数来修复它并且可以正常工作。所以这让我觉得他们是异步的。我这样做:

insertHTMLIntoIFrame( HTML ); //$("#updaterIframe").contentWindow.location.reload(true); 
setTimeout("convertToUpdatable()", 700);  

结束编辑

我的网页中的 iframe 发生了一些奇怪的事情。我的函数在我的 iframe 中搜索所有具有“可更新”类的 HTML 元素,并将这些元素转换为文本区域。

我的问题:如果我在将一些 HTML 插入 iframe 后立即调用该函数,则该函数找不到任何可更新元素(当它们在 iframe 中时)

但是

如果我通过显示 alert() 来延迟函数执行;在 iframe 中搜索可更新元素之前,我会查找并转换 iframe 中的所有元素。

这让我觉得 iframe 是异步加载的,对吗?如果不是,出了什么问题?有没有办法刷新 iframe 或确保在加载整个 iframe 之前不调用我的函数?

// I call the functions in the following order:
insertHTMLIntoIFrame( "blah");
convertToUpdatable();

function convertToUpdatable()
{
    // Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements
    //       and store their HTML element type in the class attribute
    // EG:   Before: <p class="updatable Paragraph1"/> Hello this is some text 1 </p>
    //       After : <p class='updatableElementTitle'>Paragraph1</p><textarea class="updatable Paragraph1 p"/> Hello this is some text 1 </textarea>

    if (STATE != 1 ) { return; }

    // if I dont have this line then I cant find any updatable elements in the iframe
    alert("Displaying website with updatable regions");

    $("#updaterIframe").contents().find(".updatable").each(function()
        {
            var className = this.className;
            var nodeName  = this.nodeName;
            var title     = getTitleName( this );
            $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea class='"+ className + " " + nodeName +"'>"+$(this).html() +"</textarea>");
        });

     STATE = 0; 
}

    function insertHTMLIntoIFrame( htmlSrc )
{
    try
    {
        var ifrm = document.getElementById("updaterIframe");
        ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
        ifrm.document.open();
        ifrm.document.write( htmlSrc );
        ifrm.document.close();
    }
    catch (ex) { alert("In insertHTMLIntoIFrame(): "+ex); }
}

最佳答案

是的 iframe 加载,实际上浏览器中的任何加载都是异步的。将大多数甚至闻起来像 js 中的事件的东西都考虑为异步的,你的生活将变得更加轻松。

忘记 setTimeouts,而是绑定(bind)到事件,在本例中是 iframe 对象上的 load 事件。

关于javascript - IFrame 异步加载?如果不是为什么会出现这个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7544413/

相关文章:

javascript - jQuery 在表循环中获取输入值

javascript - 在悬停时突出显示 Bootstrap 行

javascript - 如何在特定时间将菜单滑开?

javascript - 使用 bootstrap collapse 切换 glyphicon

javascript - JavaScript 中的 numpy.random.choice?

javascript - OAuth Google Analytics 客户端 API javascript

javascript - Angular Ionic UI-Router - 如何确保在嵌套状态下启动应用程序时加载所有父 View ?

jquery - 在两个 if 条件之间添加延迟

javascript - 添加图像和列表时如何更改tinymce生成的代码?

javascript - 是否有可靠的方法来检测给定元素及其子元素的所有动画何时完成?