将内容插入到iFrame中
我试图插入一些内容到一个'空白'的iFrame,但是没有插入。
HTML:
<iframe id="iframe"></iframe> JS:
 $("#iframe").ready(function() { var $doc = $("#iframe").contentWindow.document; var $body = $("<body>").text("Test"); $body.insertAfter($doc); }); 
 我正在调用ready函数,所以我不明白为什么它没有插入。 
你真的不需要jQuery的:
 var doc = document.getElementById('iframe').contentWindow.document; doc.open(); doc.write('Test'); doc.close(); 
jsFiddle演示
 如果你绝对必须使用jQuery,你应该使用contents() : 
 var $iframe = $('#iframe'); $iframe.ready(function() { $iframe.contents().find("body").append('Test'); }); 
jsFiddle演示
请不要忘记,如果您使用的是jQuery,则需要按照以下步骤挂接DOMReady函数:
 $(function() { var $iframe = $('#iframe'); $iframe.ready(function() { $iframe.contents().find("body").append('Test'); }); }); 
这应该做你想要的:
 $("#iframe").ready(function() { var body = $("#iframe").contents().find("body"); body.append('Test'); }); 
检查这个JSFiddle工作演示。
编辑:你当然可以做到一线式:
 $("#iframe").contents().find("body").append('Test'); 
您可以input(例如)div中的文本到iframe中:
 var $iframe = $('#iframe'); $iframe.ready(function() { $iframe.contents().find("body").append($('#mytext')); }); 
和divs:
 <iframe id="iframe"></iframe> <div id="mytext">Hello!</div> 
和JSFiddle演示: 链接
 如果你想在你的网页上的所有的CSS ,你可以试试这个: 
 var // Create a clone of the web-page head headClone = $('head') .clone(), // Find the head of the the iFrame we are looking for iFrameHead = $('#iframe') .contents() .find('head'); // Replace 'iFrameHead with your Web page 'head' iFrameHead .replaceWith(headClone); // You should now have all the Web page CSS in the Iframe 
祝你好运。