设置iframe innerHTML而不加载页面(使用jquery)
我想在iframe之前没有加载任何页面时动态设置iframe的内容。
我这样做:
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 = $(''); $('body').append(iFrame); var iFrameDoc = iFrame[0].contentDocument || iFrame[0].contentWindow.document; iFrameDoc.write('Some useful html
'); iFrameDoc.close();
如果您想避免使用通常不再推荐的document.write
,您可以获取帧内容以添加内容:
iframe = $('') iframeHtml = 'iframeHtml' $('body').append(iframe) iframe.contents().find('body').html(iframeHtml)
iframe = $(''); iframeHtml = 'iframeHtml'; $('body').append(iframe); iframe .contents() .html(iframeHtml);
它不起作用的原因是因为contents()
返回一个document
对象而html()
仅适用于HTMLElemnt
对象, html()
基本上是innerHTML
属性的包装器,而document
不具有这样的属性。
使用JQuery,您可以通过将html作为字符串传递来编辑iframe的属性srcdoc :
$('#iframe_id').attr("srcdoc", htmlString);