如何包含 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">Animated Buttons</a><br> <a href="howto_css_modals.asp">Modal Boxes</a><br> <a href="howto_js_animate.asp">Animations</a><br> <a href="howto_js_progressbar.asp">Progress Bars</a><br> <a href="howto_css_dropdown.asp">Hover Dropdowns</a><br> <a href="howto_js_dropdown.asp">Click Dropdowns</a><br> <a href="howto_css_table_responsive.asp">Responsive Tables</a><br>
包含 HTML
使用 w3-include-html
屬性來包含 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()
:
實例
<script> includeHTML(); </script>
包含多個 HTML 片段
您可以包含任意數量的 HTML 片段:
實例
<div w3-include-html="h1.html"></div> <div w3-include-html="content.html"></div>