我想在另一个 HTML 文件中包含 HTML 片段。我正在尝试执行此操作,因此目录中有以下文件:
include.js
include_this.html
main.html
包含以下内容:
main.html
:
<html>
<head>
<title>Whatever</title>
</head>
<body>
<h1>Including</h1>
<p>This was not included.</p>
<div w3-include-html="include_this.html"></div>
<script src="include.js"></script>
</body>
</html>
include_this.html
:
<p>This was included</p>
include.js
:
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
includeHTML();
现在,当我用任何网络浏览器打开它时,我看到的都是:
include_this.html
片段包含在
main.html
中?我使用模板文字来包装内容,这样我就可以轻松地在 HTML 中使用换行符,而不是将其放在一行或解决该问题的其他解决方案中。
const dynamicContent = document.querySelector("#dynamicContent");
const newContent = `
<p>NEW embedded content</p>
`;
dynamicContent.innerHTML = newContent;
content in HTML
<div id="dynamicContent"></div>