我想在iframe中以前没有加载页面时动态设置iframe的内容。
我正在这么做:
iframe = $('<iframe id="thepage"></iframe>');
iframeHtml = 'iframeHtml';
$('body').append(iframe);
iframe
.contents()
.html(iframeHtml);
但它不起作用,html仍然是空的。
填充帧内容的最佳方式是document.write
var dstFrame = document.getElementById('yourFrameId');
var dstDoc = dstFrame.contentDocument || dstFrame.contentWindow.document;
dstDoc.write(yourHTML);
dstDoc.close()
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();
如果你想避免使用document.write
,通常不建议再使用它,你可以在框架内容处添加内容:
iframe = $('<iframe id="thepage"></iframe>')
iframeHtml = 'iframeHtml'
$('body').append(iframe)
iframe.contents().find('body').html(iframeHtml)
使用JQuery,您可以编辑iframe的属性srcdoc,方法是将html作为字符串传递给它:
$('#iframe_id').attr("srcdoc", htmlString);
iframe = $('<iframe id="thepage"></iframe>'); iframeHtml = 'iframeHtml'; $('body').append(iframe); iframe .contents() .html(iframeHtml);
它不起作用的原因是因为contents()
返回一个document
对象,而html()
只对HTMLElemnt
对象起作用,html()
基本上是innerHTML
属性的包装器,document
没有这样的属性。
使用jQuery contents()
方法
您可以将jQuery contents()
方法与find()
、val()
和html()
方法结合使用,在iframe主体中插入文本或HTML。
var EditFrame = $("#EditWindow").contents().find('body');
var message = "Your message which needs to show in Iframe";
EditFrame.html(message);