javascript 使用innerHTML 属性显示另一个html 文件的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32938168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using innerHTML property to display content of another html file?
提问by user2789945
I am trying to set the innerHTML of one of my elements to the content of another html file that just displays plain text. Is this possible? The way I'm thinking of it is as follows, but obviously it will just set the text to that quote directly instead of displaying the contents of the file.
我正在尝试将我的一个元素的 innerHTML 设置为另一个仅显示纯文本的 html 文件的内容。这可能吗?我的想法如下,但显然它只会将文本直接设置为该引用,而不是显示文件的内容。
document.getElementById("myElement").innerHTML = "directory/file.html"
回答by Ron C
You can use the iframe
tag:
您可以使用iframe
标签:
<iframe id="myHtml" src="directory/file.html"></iframe>
You can easily change the iframe
's content by simply change it's src
attribute (it will automatically update):
您可以iframe
通过简单地更改它的src
属性来轻松更改的内容(它会自动更新):
document.getElementById('myHtml').src = 'other_file.html';
If you also want to use innerHTML
to display html from string, you can use the iframe
's srcdoc
attribute (overrides the src
attribute):
如果您还想使用innerHTML
字符串显示 html,则可以使用iframe
'ssrcdoc
属性(覆盖该src
属性):
document.getElementById('myHtml').srcdoc = '<div><p>Some HTML</p></div>';
回答by baao
You can do an ajax
call to get the files contents and put them in the html on success.
您可以ajax
调用以获取文件内容,并在成功时将它们放入 html 中。
var xhr = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', 'directory/file.html', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("myElement").innerHTML = xhr.responseText;
}
}
xhr.send();
Or using jQuery, the load()method is made for you:
或者使用 jQuery,load()方法是为你制作的:
$( "#myElement" ).load( "directory/file.html" );