如何 - 包含 HTML
了解如何在 HTML 中包含 HTML 片段。
HTML
将要包含的 HTML 保存为 .html 文件
content.html
<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">动画按钮</a><br>
<a href="howto_css_modals.asp">模态框</a><br>
<a href="howto_js_animate.asp">动画</a><br>
<a href="howto_js_progressbar.asp">进度条</a><br>
<a href="howto_css_dropdown.asp">悬停下拉菜单</a><br>
<a href="howto_js_dropdown.asp">点击下拉菜单</a><br>
<a href="howto_css_table_responsive.asp">响应式表格</a><br>
包含 HTML
HTML 包含是通过使用 **w3-include-html** 属性完成的
示例
<div w3-include-html="content.html"></div>
添加 JavaScript
HTML 包含是通过 JavaScript 完成的。
示例
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* 循环遍历所有 HTML 元素的集合:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/* 搜索具有特定属性的元素:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/* 使用属性值作为文件名进行 HTTP 请求:*/
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.";}
/* 移除属性,并再次调用此函数:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* 退出函数:*/
return;
}
}
}
</script>
在页面底部调用 includeHTML()
包含多个 HTML 片段
您可以包含任意数量的 HTML 片段