【问题标题】:Include html in another html file [duplicate]在另一个 html 文件中包含 html [重复]
【发布时间】:2016-12-14 17:42:46
【问题描述】:

我有一个 html“head”模板和一个导航模板,我想将它们包含在我网站的所有其他 html 文件中。 我找到了这篇文章:

Include another HTML file in a HTML file

我的问题是......如果我想包含标题怎么办?

例如,我有以下文件结构:

 /var/www/includes/templates/header.html
                             navigation.html

header.html 可能如下所示:

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Test Portal</title>

 </head>

在这种情况下,我仍然可以按照其他帖子中的示例创建一个 div 并通过 jquery 填充该 div 吗?

【问题讨论】:

  • 我不明白为什么它不应该像您提供的链接中描述的那样工作。

标签: javascript jquery html include


【解决方案1】:

方法一:

我认为最好的方法是使用 jQuery 将 html 内容/文件包含到另一个 html 文件中。

您可以简单地包含 jQuery.js 并使用 $("#DivContent").load("yourFile.html"); 加载 HTML 文件

例如

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#DivContent").load("another_file.html"); 
    });
    </script> 
  </head> 

  <body> 
     <div id="DivContent"></div>
  </body> 
</html>

方法二:

没有可用于包含文件的此类标签,但有一些第三方方法可用,如下所示:

<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>

<body>

<div w3-include-html="content.html"></div> 

<script>
w3IncludeHTML();
</script>

</body>
</html>

方法三:

有些人还使用了服务器端包含 (SSI):

<!--#include virtual="a.html" --> 

【讨论】:

  • 似乎对我有用
  • 方法2好像改了,这里是最新文档的链接w3schools.com/w3js/w3js_html_include.asp
  • @mattruma,可能,我给出这个答案已经 3 年了。正如我所说,方法 2 只是第三方插件/方法..
  • 我认为#3 是 C++ 并且我的网络服务器不支持 (?),而且我不是 #2 的粉丝,包括一个额外的 .js 仅用于一个功能,但 #1 效果很好对我来说......一旦我added a callback,代码执行将在文件完全加载之前不会继续(因为我需要立即与加载的元素进行交互)。
【解决方案2】:

使用&lt;object&gt;标签:

<object data="filename.html"></object>

【讨论】:

  • 太棒了!干净简单。
  • 它在body标签中显示了一个可滚动的窗口,由html标签包围,带有head,因此它创建了一个新的dom
  • 不错!然而,一个小限制是,主机页面的 CSS 样式不适用于插入的 HTML 文本(至少对于 Chromium 87.0/Ubuntu 20 上的我来说不是)。除非样式包含在导入的文本中。
  • 它不起作用,它启动了一个 Flash emualtor
【解决方案3】:

我需要包含许多文件。所以我创建了以下脚本:

<script>
  $(function(){
    $('[id$="-include"]').each(function (e){
        $(this).load("includes\\" + $(this).attr("id").replace("-include", "") +  ".html");
    });
  });
</script>

例如,使用 div 为插入放置一个占位符。

&lt;div id="example-include"&gt;&lt;/div&gt;

为我需要包含的所有文件创建了“包含”文件夹。创建文件“example.html”。 它适用于任意数量的包含。您只需使用命名约定并将所有包含的文件放在正确的文件夹中。

【讨论】:

    【解决方案4】:

    使用 HTML 标签。

    我遇到过类似的问题,然后我用了

    iframe src = "b.html" height="80px" width="500px" >

    【讨论】:

    • 这是基于原始 html 的解决方案,不需要依赖 Jquery。 @Akash 谢谢
    【解决方案5】:

    对于任何对 Web 组件方法感兴趣的人:

    <html-include src="my-html.html"></html-include>
    

    以及对应的JS:

    class HTMLInclude extends HTMLElement {
      constructor() {
        super();
        this.innerHTML = "Loading...";
        this.loadContent();
      }
    
      async loadContent() {
        const source = this.getAttribute("src");
        if (!source) {
          throw new Error("No src attribute given.");
        }
        const response = await fetch(source);
        if (response.status !== 200) {
          throw new Error(`Could not load resource: ${source}`);
        }
        const content = await response.text();
        this.innerHTML = content;
      }
    }
    
    window.customElements.define("html-include", HTMLInclude);
    

    请注意,可以使用影子 DOM 做一些好事,以确保加载内容的样式不会影响外部页面。

    上面的代码是非常“现代”的 JS,你可能不想在没有一些 polyfills/babel 转译的情况下直接使用上面的代码。

    【讨论】:

    • 如何查询my-html.html中的一些元素?我无法查询该文件中的元素,因为当我们查询时,它不会出现在 DOM 中
    【解决方案6】:

    这类似于另一种自定义标签解决方案,但这个解决方案使用开始和结束标签之间的文本作为包含路径/url。另一种解决方案使用src 属性。

    <html-include> ./partials/toolbar.html </html-include>
    

    元素实现有点棘手:

    # -- ./js/html-include.js --
    
    class HTMLInclude extends HTMLElement {
        constructor(src) {
            super();
            this.attachShadow({mode: "open"});
            if (src) { 
                this.textContent = src;
            }
            setTimeout(() => this._load());
        }
        async _load() {
            let src = this.textContent.trim();
    
            if (!src) {
                throw new Error("URL missing between <html-import> tags.");
            } 
            let rsp = await fetch(src);
    
            if (rsp.status != 200) {
                throw new Error(`Failed to load file (${src}) for <html-import>.`);
            }
            this.shadowRoot.innerHTML = await rsp.text();
        }
    }
    customElements.define("html-include", HTMLInclude);
    

    setTimeout() 是必要的,因为如果过早访问 this.textContent,可能会包含页面的所有前面文本(在 Chrome/Chromium 上可见)。推迟访问修复。

    这是合并到页面中的样子:

    <html>
        <head>
            <link rel="stylesheet" href="./css/index.css">
            <script type="text/javascript" src="./js/html-include.js"></script>
        </head>
        <body>
            <html-include> ./partials/toolbar.html   </html-include>
            <html-include> ./partials/side-menu.html </html-include>
            <html-include> ./partials/statusbar.html </html-include>
        </body>
    </html>
    

    CSS 样式应正确应用于新导入的 HTML。

    这个元素也可以通过将 URL 传递给导入文件来从 JS 创建。

    let wgthost = document.getElementById("tgt");
    wgthost.appendChild(new HTMLInclude("./partials/mywidget.html"));
    

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 2013-06-13
      • 2013-07-28
      • 2013-06-25
      • 1970-01-01
      • 2019-01-04
      • 2011-01-21
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多