[英]How to copy iframe content to div?
請參閱下面的代碼片段。 我希望 iframe 中的輸出文本顯示在 #source div 中。 我正在為此苦苦掙扎,並感謝任何想法。 如何將 iframe 中的輸出文本復制到 div? (腳本在 div #show 中寫入“Can see text!”如果 div #sourcediv 包含“Text”,否則“Cannot see text!”。)
<html> <body> <div id="source"></div> <div id="show"></div> <script> if (document.getElementById('source').innerHTML.indexOf("Text") != -1) {document.getElementById('show').innerHTML="Can see text!";} else{document.getElementById('show').innerHTML="Cannot see text!";} </script> <iframe id="iframe" src="http://majaulrika.esy.es/text.txt"> </body> </html>
請記住,您的iframe與您的頁面位於同一域中:
// Get your iframe element
var iframe = document.getElementById('iframe');
// Access contents of it like this
var iframeContent = iframe.contentWindow.document;
// Get your div element
var content = document.getElementById('source');
// set contents of this div to iframe's content
content.innerHTML = iframeContent.innerHTML;
根據您執行此操作的時間,可能值得等到 iframe 加載:
iframe.onload = function() { /* put the above code here */ }
進一步您的評論:
從文件中獲取內容的更好解決方案是使用 ajax。
這是使用 ajax 和 jQuery 的簡單方法。
$.ajax({
url: 'http://output.jsbin.com/sebusu',
success: function(data) {
$('#source').html(data);
$('#show').text(function(){
if (data.indexOf('Text') != -1) {
return 'Can see text!';
}
else {
return "Can't see text!";
}
});
},
error: function(){
console.log(error);
}
});
<div id="source"></div>
<div id="show"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
同樣,您只能為您的網站調用 ajax(有一些例外)
$("#my_iframe").on('load', function() {
$("#my_div").empty().append($('#my_iframe').contents().find('body').html());
});
注意:'body' 可以是 iframe 內的任何內容,如果您只想要一個特定的 div,您可以使用 'body' 或 'html' 執行 '#div_inside_iframe' 而不是 'body' 將 iframe 內的所有內容復制到目標 div .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.