问题描述
好吧,这很简单,但我有点需要菜鸟的帮助.
ok, this is simple, but I kinda need a noob's help.
我想做一些简单的事情:将 HTML 文件内容分配给 JS 变量,然后使用 innerHTML 属性将此 html 代码传递到页面元素中.
I'd like to do something simple:To assign an HTML file contents to a JS var, and then to pass this html code into a page element using the innerHTML property.
这可以通过 HtmlHTTPRequest 轻松完成,但是,我不确定我应该使用的确切代码是什么.
This can be done easily with HtmlHTTPRequest, however, i'm not sure what is the exact code i should use.
这是我想要实现的目标:
here's what I'd like to achieve:
var foo = contents_of_an_html_file (file.html)
document.getElementById('preview').innerHTML = foo;
会很高兴你的启蒙:)
推荐答案
这里是一个带 iframe 的函数,没有 JS lib,没有 ajax.
Here is a function with an iframe, no JS lib, no ajax.
function getFile(src, target){
var ifr = document.createElement('IFRAME');
ifr.onload = function(e){
target.innerHTML =
(ifr.contentDocument||ifr.contentWindow.document).body.innerHTML;
document.body.removeChild(ifr);
ifr = null;
};
ifr.src = src;
ifr.style.display = 'none';
document.body.appendChild(ifr);
}
并使用它:
getFile('file.html', document.getElementById('preview'));
如果需要,您可以获取除 body
标签之外的页面元素.
You can get other elements of the page than the body
tag if needed.
这篇关于如何将文件内容分配到 Javascript var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!