我有几个具有相同页脚的html页面。只用JavaScript,我能在其中导入另一个html页面吗?
我有几个具有相同页脚的html页面。只用JavaScript,我能在其中导入另一个html页面吗?
以下是如何使用纯JavaScript为页面添加页脚的方法。
使用fetch
和insertAdjacentHTML
函数的2022代码示例:
async function addFooter() {
const resp = await fetch("footer.htm");
const html = await resp.text();
document.body.insertAdjacentHTML("beforeend", html);
}
2011年的原始代码,使用XMLHttpRequest
和innerHTML
:
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function () {
document.body.innerHTML += ajax.responseText;
}
ajax.open("GET", "footer.htm");
ajax.send();
即使在今天,2011年的代码仍然可以在所有浏览器中运行,但fetch
更加直观,并且允许您避免编写事件处理程序回调。 insertAdjacentHTML
也适用于所有浏览器,因此您可以使用它或者innerHTML
,使用这两个示例之一。只有fetch
是新的,在IE中需要polyfill才能正常工作。
fetch
而不是XMLHttpRequest
更为常见。我将对我的答案进行2022年的更新。 - gilly3如上所述,一种方法是使用jQuery的load函数。我恰好现在也在做完全相同的事情,所以将发布一个快速示例。
使用jQuery:
$("#yourDiv").load('readHtmlFromHere.html #readMe');
你的readHtmlFromHere.html页面将包含:
<div><div id="readMe"><p>I'm some text</p></div></div>
div
包装器。例如 <div id='yourDiv'>HTML 将在此处注入。</div>
。 - Ricky根据这个答案的示例(是该问题的答案之一),我创建了这个小的可重用函数:
/**
* Render the array of html files, to the
* selected container.
* @param {*} pages - array of html file names
* @param {*} container - HTML element name
*/
function render(pages, container) {
const template = document.createElement("template");
var ajax = new XMLHttpRequest();
pages.forEach(element => {
// this is the route where the files are stored
ajax.open("GET", `./view/shared/${element}.html`, false);
ajax.send();
template.innerHTML += ajax.responseText;
});
document.querySelector(container).append(template.content);
}
export { render };
index.js
文件中使用它,就像这样:import { render } from "./tools/render.js";
var headerContent = ["siteName", "navbar"];
render(headerContent, "header");
siteName.html
和navbar.html
渲染到站点根目录的index.html
文件的<header>
标签中。fetch("MyHTMLFile.html").then((response) => {
response.text().then((text) => {
targetHTMLElement.innerHTML = text;
});
})
你肯定可以这样做,但如果你只是在进行模板编写,我建议你在服务器上完成。