设置iframe innerHTML而不加载页面(使用jquery)

Let*_*eto 8 javascript iframe jquery

我想在iframe之前没有加载任何页面时动态设置iframe的内容.

我这样做:

iframe = $('<iframe id="thepage"></iframe>');

iframeHtml = 'iframeHtml';
$('body').append(iframe);

iframe
.contents()
.html(iframeHtml);
Run Code Online (Sandbox Code Playgroud)

但它没有用,html仍然是空的.

new*_*ver 22

填充框架内容的最佳方法是 document.write

var dstFrame = document.getElementById('yourFrameId');
var dstDoc = dstFrame.contentDocument || dstFrame.contentWindow.document;
dstDoc.write(yourHTML);
dstDoc.close()
Run Code Online (Sandbox Code Playgroud)

UPD:就是这样

var iFrame = $('<iframe id="thepage"></iframe>');
$('body').append(iFrame);

var iFrameDoc = iFrame[0].contentDocument || iFrame[0].contentWindow.document;
iFrameDoc.write('<p>Some useful html</p>');
iFrameDoc.close();
Run Code Online (Sandbox Code Playgroud)


jks*_*der 9

如果您想避免使用document.write(通常不再推荐使用),您可以获取帧内容以添加内容:

iframe = $('<iframe id="thepage"></iframe>')
iframeHtml = 'iframeHtml'
$('body').append(iframe)
iframe.contents().find('body').html(iframeHtml)
Run Code Online (Sandbox Code Playgroud)


Gad*_*erg 7

使用JQuery,您可以通过将html作为字符串传递给iframe,从而编辑iframe的属性srcdoc

$('#iframe_id').attr("srcdoc", htmlString);
Run Code Online (Sandbox Code Playgroud)