HTML主页?如何在另一个HTML文件中包含一个HTML文件?

时间:2018-07-27 02:59:30

标签: html css

我有一个全部由Github Pages托管的HTML / CSS网站(它似乎仅支持“静态页面”?)。如何将我的主HTML页面(页眉和页脚)的HTML包含到另一个HTML页面中?我愿意使用HTML,Javascript,Jquery等来完成此操作(只要我的页面仍然符合“静态”标准)。谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

包含HTML

包含HTML是通过使用include-html属性完成的:

<div 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("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("include-html");
          includeHTML();
        }
      } 
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
}
</script>

调用页面底部的includeHTML():

<script>
includeHTML();
</script>

参考:https://www.w3schools.com/howto/howto_html_include.asp