目录

如何 - 包含 HTML


了解如何在 HTML 中包含 HTML 片段。


HTML

将要包含的 HTML 保存到 .html 文件中:

内容.html

<a href="howto_google_maps.html">Google Maps</a><br>
<a href="howto_css_animate_buttons.html">Animated Buttons</a><br>
<a href="howto_css_modals.html">Modal Boxes</a><br>
<a href="howto_js_animate.html">Animations</a><br>
<a href="howto_js_progressbar.html">Progress Bars</a><br>
<a href="howto_css_dropdown.html">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.html">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.html">Responsive Tables</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;
  /* 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;
    }
  }
}
</script>

在页面底部调用 includeHTML():

示例

<script>
includeHTML();
</script>
亲自试一试 »


包含许多 HTML 片段

您可以包含任意数量的 HTML 片段:

示例

<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
亲自试一试 »