是否可以在多个页面上像模板一样重用 HTML?

新手上路,请多包涵

我在一个网站上有几个页面,每个页面都使用相同的标题。我想知道是否有某种方法可以简单地引用带有 html 标题的文件,就像在这个伪代码中一样:

 <!-- Main Page -->

<body>
  <html_import_element src = "myheadertemplate.html">
<body>

然后在一个单独的文件中:

 <!-- my header template html -->

<div>
  <h1>This is my header</h1>
  <div id = "navbar">
    <div class = "Tab">Home</div>
    <div class = "Tab">Contact</div>
  </div>
</div>

这样我就可以编写一次标题 html,然后通过编写一个简单的标记将它导入到我需要它的每个页面中。这可能吗?我可以用 XML 做到这一点吗?

原文由 Frank 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 305
2 个回答

所以,经过很长一段时间后,我实际上找到了一种使用 AJAX 来执行此操作的方法。 HTML 导入是一个很好的解决方案,但截至 04/2017 严重缺乏跨浏览器的支持,所以我想出了一个更好的解决方案。这是我的源代码:

 function HTMLImporter() {}

HTMLImporter.import = function (url) {
  var error, http_request, load, script;

  script =
    document.currentScript || document.scripts[document.scripts.length - 1];

  load = function (event) {
    var attribute, index, index1, new_script, old_script, scripts, wrapper;

    wrapper = document.createElement("div");
    wrapper.innerHTML = this.responseText;

    scripts = wrapper.getElementsByTagName("SCRIPT");

    for (index = scripts.length - 1; index > -1; --index) {
      old_script = scripts[index];

      new_script = document.createElement("script");
      new_script.innerHTML = old_script.innerHTML;

      for (index1 = old_script.attributes.length - 1; index1 > -1; --index1) {
        attribute = old_script.attributes[index1];
        new_script.setAttribute(attribute.name, attribute.value);
      }

      old_script.parentNode.replaceChild(new_script, old_script);
    }

    while (wrapper.firstChild) {
      script.parentNode.insertBefore(
        wrapper.removeChild(wrapper.firstChild),
        script
      );
    }

    script.parentNode.removeChild(script);

    this.removeEventListener("error", error);
    this.removeEventListener("load", load);
  };

  error = function (event) {
    this.removeEventListener("error", error);
    this.removeEventListener("load", load);

    alert("there was an error!");
  };

  http_request = new XMLHttpRequest();
  http_request.addEventListener("error", error);
  http_request.addEventListener("load", load);
  http_request.open("GET", url);
  http_request.send();
};

现在,当我想将 HTML 导入另一个文档时,我所要做的就是添加一个脚本标签,如下所示:

 <script>HTMLImporter.import("my-template.html");</script>

我的函数实际上会将用于调用导入的脚本标记替换为 my-template.html 的内容,并且它将执行在模板中找到的任何脚本。模板不需要特殊格式,只需编写您希望在代码中出现的 HTML。

原文由 Frank 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以用下面的这种方式来做。

 <head>
  <link rel="import" href="myheadertemplate.html">
</head>

你可以在哪里拥有 myheadertemplate.html

 <div>
  <h1>This is my header</h1>
  <div id = "navbar">
    <div class = "Tab">Home</div>
    <div class = "Tab">Contact</div>
  </div>
</div>

然后你可以在下面的 JS 中使用它

var content = document.querySelector('link[rel="import"]').import;

原文由 Shadab K 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题