猿问

Javascript 创建 iframe 设置内容然后从一个函数返回它

我需要动态创建一个 iframe,设置它的 html,然后将它作为一个函数返回,以便以后可以使用 newAdUnit() 调用它。现在它返回 [object HTMLIFrameElement]。我试图找出一种方法来从一个函数中完成这一切。这样做的原因是我正在设置需要动态加载的广告。单个函数会使我的代码更简洁,因为我可以用多种不同的方式调用它。有任何想法吗?


<script>

function newAdUnit(size) {

    var iframe = document.createElement('iframe');

    iframe.onload = function() {

        iframe = iframe.contentWindow.document;

        var html = '<body>This is a test</body>';

        iframe.open();

        iframe.write(html);

        iframe.close();

    };

    return iframe;

}

</script>

<div id="test">

<script>document.getElementById("test").innerHTML = newAdUnit()</script>

</div>


函数式编程
浏览 256回答 2
2回答

慕雪6442864

您应该只.innerHTML在要添加的内容是 HTML 字符串时使用。但是,在您的情况下,您有一个HTMLIFrameElement对象,因此.innerHTML在这种情况下不能使用。目前,Javascript 正在隐式调用.toString()由 返回的元素对象newAdUnit(),这会导致[object HTMLIFrameElement].相反,当你想将一个节点元素添加到另一个元素时,你可以.appendChild()像这样使用:<div id="test"></div><script>&nbsp; function newAdUnit(size) {&nbsp; &nbsp; var iframe = document.createElement('iframe');&nbsp; &nbsp; iframe.onload = function() {&nbsp; &nbsp; &nbsp; iframe = iframe.contentWindow.document;&nbsp; &nbsp; &nbsp; var html = '<body>This is a test. The size is ' + size + '</body>';&nbsp; &nbsp; &nbsp; iframe.open();&nbsp; &nbsp; &nbsp; iframe.write(html);&nbsp; &nbsp; &nbsp; iframe.close();&nbsp; &nbsp; };&nbsp; &nbsp; return iframe;&nbsp; }&nbsp; document.getElementById("test").appendChild(newAdUnit(10));</script>

慕后森

如果您在当前操作中使用JQuery,将会非常容易。下面的代码显示了如何<html>&nbsp; <head>&nbsp; <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>&nbsp; <script>&nbsp; $(document).ready(function() {&nbsp; &nbsp; function newAdUnit(obj) {&nbsp; &nbsp; &nbsp; &nbsp; var iframe = document.createElement('iframe');&nbsp; &nbsp; &nbsp; &nbsp; iframe.onload = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; iframe = iframe.contentWindow.document;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var html = '<body>This is a test</body>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; iframe.open();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; iframe.write(html);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; iframe.close();&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; $(obj).append(iframe);&nbsp; &nbsp; }&nbsp; &nbsp; newAdUnit($('#test'));&nbsp; });&nbsp; </script>&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; <div id="test">&nbsp; &nbsp; </div>&nbsp; </body></html>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答