简体   繁体   English

将HTML动态添加到iFrame-Javascript

[英]Dynamically Adding HTML into an iFrame - Javascript

I'm attempting to dynamically create an iFrame and add HTML into it from the current document. 我正在尝试动态创建iFrame并将HTML添加到当前文档中。 The iFrame gets created successfully, but when the function gets to the point where it needs to add the HTML in, it doesn't do it. iFrame创建成功,但是当功能达到需要添加HTML的地步时,它不会执行此操作。

Here's my code: 这是我的代码:

function createiFrame(min, max, key) {
    console.log("Max-Width", max);

    //CREATING A CLASS FOR THE IFRAME
    var iframeClass = key + "-" + max;
    //var path = window.location.pathname;
    //var page = path.split("/").pop();

    //ADDING AN IFRAME INTO THE DOCUMENT AND ADDING ON THE CLASS
    $(document).ready(function() {
        $('<iframe>', {
            width: max
        }).addClass(iframeClass).prependTo('body');
    });


    var requiredHTML = document.getElementById('container').innerHTML;
    console.log("RequiredHTML", requiredHTML);

    //ADDING THE COLLECTED HTML INTO THE IFRAME -- THIS IS WHERE 
    //IT STOPS WORKING
    $('.' + iframeClass).ready(function() {
        console.log("iFrame ready");
        $('.' + iframeClass).contents().find('body').html("<p>Testing it out</p>");
    });

    var $head = document.getElementsByTagName('head')[0].innerHTML;
    $(document).ready(function() {
        $('.' + iframeClass).contents().find('head').append($head);
    });


}

EDIT 编辑

I've realised this problem is occurring because when I try to run that code, the DOM isn't ready yet. 我已经意识到出现此问题的原因是,当我尝试运行该代码时,DOM还没有准备好。

So new question; 如此新的问题;

How do I get the DOM ready? 如何准备DOM?

check out this post: addEventListener to iFrame 看看这篇文章: addEventListener到iFrame

you need to use $('#myIFrame').load(function(){ .... 您需要使用$('#myIFrame')。load(function(){....

$('.' + iframeClass).ready(function() {
    ...
}

Doesn't work because an iframe being ready doesn't trigger the Event 'DOMContentLoaded' which .ready() is waiting for. 不起作用,因为准备就绪的iframe不会触发.ready()等待的事件'DOMContentLoaded'。 You'll need to refer directly to a document, which will then trigger the DOMContentLoaded event. 您需要直接引用文档,该文档随后将触发DOMContentLoaded事件。 This should work based on that. 基于此应该工作。

$(iframeClass document).ready(function() {
    ...
}

I will stress though that this isn't something that I've tried before, but it seems like it's just a matter of which document you're referring to. 我会强调一点,尽管这不是我以前尝试过的事情,但似乎只是您要参考哪个文档的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM