【发布时间】:2009-03-06 23:30:11
【问题描述】:
我可以创建一个空的 iframe 作为占位符,以便稍后将 html 插入其中吗?
换句话说,假设我有一个带有 id 的空 iframe,
如何在其中插入 html?
我正在使用 jquery,如果这样更容易的话。
【问题讨论】:
标签: javascript jquery html iframe
我可以创建一个空的 iframe 作为占位符,以便稍后将 html 插入其中吗?
换句话说,假设我有一个带有 id 的空 iframe,
如何在其中插入 html?
我正在使用 jquery,如果这样更容易的话。
【问题讨论】:
标签: javascript jquery html iframe
你也可以不使用 jQuery:
var iframe = document.getElementById('iframeID');
iframe = iframe.contentWindow || ( iframe.contentDocument.document || iframe.contentDocument);
iframe.document.open();
iframe.document.write('Hello World!');
iframe.document.close();
jQuery 的 html 从插入的 HTML 中去除 body、html 和 head 标签。
【讨论】:
<html foo="bar"></html>。请注意,iframe 必须插入到其父文档中。
iframe = iframe.contentWindow || ( iframe.contentDocument.document || iframe.contentDocument);
查看此页面的来源:http://mg.to/test/dynaframe.html 它似乎完全符合您的要求。
$(function() {
var $frame = $('<iframe style="width:200px; height:100px;">');
$('body').html( $frame );
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html('<h1>Test</h1>');
}, 1 );
});
【讨论】:
body 元素,当您可能需要head 元素,甚至是html 元素的属性时。
不,不是。您可以像这样修改脚本:
$(function() {
var $frame = $('iframe');
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html('<h1>Test</h1>');
}, 1 );
});
【讨论】:
iframeElementContainer = document.getElementById('BOX_IFRAME').contentDocument;
iframeElementContainer.open();
iframeElementContainer.writeln("<html><body>hello</body></html>");
iframeElementContainer.close();
【讨论】:
是的,我知道这是可能的,但主要问题是我们无法处理来自外部的框架,我已经加载了其他东西。
$(function() {
var $frame = $('<iframe style="width:200px; height:100px;">');
$('body').html( $frame );
setTimeout( function() {
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html('<h1>Test</h1>');
}, 1 );
});
但如果我们以
开头<iframe src="http:/www.hamrobrt.com">
<---Your Script to put as you like--->
那就不可能了。
【讨论】:
我有同样的问题,我必须在没有 iframe 的 SRC 属性的情况下从数据库动态显示 iframe 中的 html 代码 sn-p 并且我用以下代码修复了同样的问题
我希望这对有同样要求的人有所帮助。
HTML:
<iframe src="" frameborder="0" class="iframe"></iframe>
<iframe src="" frameborder="0" class="iframe"></iframe>
<iframe src="" frameborder="0" class="iframe"></iframe>
<iframe src="" frameborder="0" class="iframe"></iframe>
JS
<script>
var doc,$body;
var txt = Array(
'<style>body{background-color:grey} h1{background-color:red;font-weight:900}</style><h1>Cool!!! this is text for</h1><p>First Iframe</p>',
'<style>body{background-color:pink}h1{background-color:green;font-weight:200}</style><h1>Cool This is Text for</h1><p> second Iframe',
'<style>body{background-color:yellow}h1{font-weight:400}</style><h1>Cool..... This is text FOR : </h1> <div>3rd Iframe</div>',
'<style>body{background-color:blue} h1{font-weight:400}</style><h1>Cool This is text for Fourth iframe</h1>'
);
$('.iframe').each(function(index,value){
doc = $('iframe')[index].contentWindow.document;
$body = $('body',doc);
$body.html(txt[index]);
});
</script>
【讨论】: