【问题标题】:HTML master page? How to include one HTML file in another HTML file?HTML 母版页?如何在另一个 HTML 文件中包含一个 HTML 文件?
【发布时间】:2019-01-04 02:48:57
【问题描述】:

我有一个由 Github Pages 托管的全 HTML/CSS 网站(它似乎只支持“静态页面”?)。如何将我的主 HTML 页面(页眉和页脚)的 HTML 包含到另一个 HTML 页面中?我愿意使用 HTML、Javascript、Jquery 等来实现这一点(只要我的页面仍然符合“静态”的条件)。谢谢你的帮助。

【问题讨论】:

  • 你会考虑使用<iframe>吗?
  • 听起来像一个 JavaScript SPA 框架将是要走的路。我推荐 Aurelia 或 React。结果在内容意义上将是非常静态的。只需几个 JS 文件,但网站会随心所欲地动态

标签: html css


【解决方案1】:

包含 HTML

通过使用 include-html 属性来包含 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

【讨论】:

  • @Ryan 这是自定义属性
猜你喜欢
  • 2013-06-25
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 2013-12-01
  • 1970-01-01
  • 2011-11-24
相关资源
最近更新 更多