首页 文章

在HTML文件中包含另一个HTML文件

提问于
浏览
520

我有2个HTML文件,假设 a.htmlb.html . 在 a.html 我想包括 b.html .

在JSF中,我可以这样做:

<ui:include src="b.xhtml" />

这意味着在 a.xhtml 文件中,我可以包含 b.xhtml .

我们怎么能在 *.html 文件中这样做?

28 回答

  • 28

    如果需要包含来自某个文件的html内容,则以下工作:例如,以下行将在OBJECT定义发生的位置包含piece_to_include.html的内容 .

    ...text before...
    <OBJECT data="file_to_include.html">
    Warning: file_to_include.html could not be included.
    </OBJECT>
    ...text after...
    

    参考:http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4

  • 1

    要插入指定文件的内容:

    <!--#include virtual="filename.htm"-->
    
  • 43

    我来到这个主题寻找类似的东西,但与lolo提出的问题有点不同 . 我想构建一个HTML页面,其中包含指向其他页面的链接的字母菜单,并且每个其他页面可能存在也可能不存在,并且创建它们的顺序可能不是按字母顺序排列的(甚至也不是数字) . 另外,像Tafkadasoh一样,我不想用jQuery膨胀网页 . 在研究了这个问题并进行了几个小时的实验之后,这里有什么对我有用,并附有相关评论:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1">
      <meta name="Author" content="me">
      <meta copyright="Copyright" content= "(C) 2013-present by me" />
      <title>Menu</title>
    
    <script type="text/javascript">
    <!--
    var F000, F001, F002, F003, F004, F005, F006, F007, F008, F009,
        F010, F011, F012, F013, F014, F015, F016, F017, F018, F019;
    var dat = new Array();
    var form, script, write, str, tmp, dtno, indx, unde;
    
    /*
    The "F000" and similar variables need to exist/be-declared.
    Each one will be associated with a different menu item,
    so decide on how many items maximum you are likely to need,
    when constructing that listing of them.  Here, there are 20.
    */
    
    
    function initialize()
    { window.name="Menu";
      form = document.getElementById('MENU');
      for(indx=0; indx<20; indx++)
      { str = "00" + indx;
        tmp = str.length - 3;
        str = str.substr(tmp);
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = str + ".js";
        form.appendChild(script);
      }
    
    /*
    The for() loop constructs some <script> objects
    and associates each one with a different simple file name,
    starting with "000.js" and, here, going up to "019.js".
    It won't matter which of those files exist or not.
    However, for each menu item you want to display on this
    page, you will need to ensure that its .js file does exist.
    
    The short function below (inside HTML comment-block) is,
    generically, what the content of each one of the .js files looks like:
    <!--
    function F000()
    { return ["Menu Item Name", "./URLofFile.htm", "Description string"];
    }
    -->
    
    (Continuing the remarks in the main menu.htm file)
    It happens that each call of the form.appendChild() function
    will cause the specified .js script-file to be loaded at that time.
    However, it takes a bit of time for the JavaScript in the file
    to be fully integrated into the web page, so one thing that I tried,
    but it didn't work, was to write an "onload" event handler.
    The handler was apparently being called before the just-loaded
    JavaScript had actually become accessible.
    
    Note that the name of the function in the .js file is the same as one
    of the the pre-defined variables like "F000".  When I tried to access
    that function without declaring the variable, attempting to use an
    "onload" event handler, the JavaScript debugger claimed that the item
    was "not available".  This is not something that can be tested-for!
    However, "undefined" IS something that CAN be tested-for.  Simply
    declaring them to exist automatically makes all of them "undefined".
    When the system finishes integrating a just-loaded .js script file,
    the appropriate variable, like "F000", will become something other
    than "undefined".  Thus it doesn't matter which .js files exist or
    not, because we can simply test all the "F000"-type variables, and
    ignore the ones that are "undefined".  More on that later.
    
    The line below specifies a delay of 2 seconds, before any attempt
    is made to access the scripts that were loaded.  That DOES give the
    system enough time to fully integrate them into the web page.
    (If you have a really long list of menu items, or expect the page
    to be loaded by an old/slow computer, a longer delay may be needed.)
    */
    
      window.setTimeout("BuildMenu();", 2000);
      return;
    }
    
    
    //So here is the function that gets called after the 2-second delay  
    function BuildMenu()
    { dtno = 0;    //index-counter for the "dat" array
      for(indx=0; indx<20; indx++)
      { str = "00" + indx;
        tmp = str.length - 3;
        str = "F" + str.substr(tmp);
        tmp = eval(str);
        if(tmp != unde) // "unde" is deliberately undefined, for this test
          dat[dtno++] = eval(str + "()");
      }
    
    /*
    The loop above simply tests each one of the "F000"-type variables, to
    see if it is "undefined" or not.  Any actually-defined variable holds
    a short function (from the ".js" script-file as previously indicated).
    We call the function to get some data for one menu item, and put that
    data into an array named "dat".
    
    Below, the array is sorted alphabetically (the default), and the
    "dtno" variable lets us know exactly how many menu items we will
    be working with.  The loop that follows creates some "<span>" tags,
    and the the "innerHTML" property of each one is set to become an
    "anchor" or "<a>" tag, for a link to some other web page.  A description
    and a "
    " tag gets included for each link. Finally, each new <span> object is appended to the menu-page's "form" object, and thereby ends up being inserted into the middle of the overall text on the page. (For finer control of where you want to put text in a page, consider placing something like this in the web page at an appropriate place, as preparation: <div id="InsertHere"></div> You could then use document.getElementById("InsertHere") to get it into a variable, for appending of <span> elements, the way a variable named "form" was used in this example menu page. Note: You don't have to specify the link in the same way I did (the type of link specified here only works if JavaScript is enabled). You are free to use the more-standard "<a>" tag with the "href" property defined, if you wish. But whichever way you go, you need to make sure that any pages being linked actually exist! */ dat.sort(); for(indx=0; indx<dtno; indx++) { write = document.createElement('span'); write.innerHTML = "<a onclick=\"window.open('" + dat[indx][1] + "', 'Menu');\" style=\"color:#0000ff;" + "text-decoration:underline;cursor:pointer;\">" + dat[indx][0] + "</a> " + dat[indx][2] + "
    "; form.appendChild(write); } return; } // --> </script> </head> <body onload="initialize();" style="background-color:#a0a0a0; color:#000000; font-family:sans-serif; font-size:11pt;"> <h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;MENU <noscript>
    <span style="color:#ff0000;"> Links here only work if
    your browser's JavaScript
    support is enabled.</span>
    </noscript></h2> These are the menu items you currently have available:

    <form id="MENU" action="" onsubmit="return false;"> <!-- Yes, the <form> object starts out completely empty --> </form> Click any link, and enjoy it as much as you like.
    Then use your browser's BACK button to return to this Menu,
    so you can click a different link for a different thing.


    <small>This file (web page) Copyright (c) 2013-present by me</small> </body> </html>
  • 0

    如果你使用像django / bootle这样的框架,他们经常会发布一些模板引擎 . 假设您使用瓶子,默认模板引擎是SimpleTemplate Engine . 以下是纯html文件

    $ cat footer.tpl
    <hr> <footer>   <p>&copy; stackoverflow, inc 2015</p> </footer>
    

    您可以在主文件中包含footer.tpl,例如:

    $ cat dashboard.tpl
    %include footer
    

    除此之外,您还可以将参数传递给dashborard.tpl .

  • 15

    好吧,如果您想要做的就是将文本从单独的文件放入页面(文本中的标签也应该有效),您可以这样做(主页上的文本样式 - test.html - 仍然可以使用) :

    test.html

    <html>
    <body>
    <p>Start</p>
    
    <p>Beginning</p>
    
    <div>
    <script language="JavaScript" src="sample.js"></script>
    </div>
    
    <p>End</p>
    
    </body>
    </html>
    

    sample.js

    var data="Here is the imported text!";
    document.write(data);
    

    毕竟,您始终可以重新创建自己想要的HTML标记 . 除非你想做更多的事情,否则需要服务器端脚本来从另一个文件中获取文本 .

    无论如何,我开始使用它的原因是如果我更新大量HTML文件中常见的描述,我只需要更新一个文件来执行它( .js 文件)而不是每个单独的HTML文件包含文本 .

    因此,总而言之,更简单的解决方案是在一个变量中导入带有 .html 文件内容的 .js 文件,而不是导入 .html 文件(并将内容写入您调用脚本的屏幕) .

    谢谢你的提问 .

  • 52

    html5rocks.com有一个关于这个东西的非常好的教程,这可能有点晚了,但我自己并没有实际在本地加载它们并在你的机器上测试它们 . 但你可以做的是使用顶部html5rocks链接上提供的polyfill,或者按照他们的教程 . 有了一点JS魔术,你可以这样做:

    var link = document.createElement('link');
     if('import' in link){
         //Run import code
         link.setAttribute('rel','import');
         link.setAttribute('href',importPath);
         document.getElementsByTagName('head')[0].appendChild(link);
         //Create a phantom element to append the import document text to
         link = document.querySelector('link[rel="import"]');
         var docText = document.createElement('div');
         docText.innerHTML = link.import;
         element.appendChild(docText.cloneNode(true));
     } else {
         //Imports aren't supported, so call polyfill
         importPolyfill(importPath);
     }
    

    这将创建链接(可以更改为已设置的有用链接元素),设置导入(除非您已经拥有它),然后追加它 . 然后它将从那里获取并以HTML格式解析文件,然后将其附加到div下的所需元素 . 这一切都可以根据您的需要从附加元素更改为您正在使用的链接 . 我希望这有所帮助,如果不使用jQuery或W3.js这样的库和框架,更新,更快的方法可能会变得无关紧要 .

    UPDATE: 这将抛出错误,表示本地导入已被CORS策略阻止 . 由于深层网络的属性,可能需要访问深层网络以便能够使用它 . (意思没有实际用途)

  • 0

    在我看来,最好的解决方案使用jQuery:

    a.html

    <html> 
      <head> 
        <script src="jquery.js"></script> 
        <script> 
        $(function(){
          $("#includedContent").load("b.html"); 
        });
        </script> 
      </head> 
    
      <body> 
         <div id="includedContent"></div>
      </body> 
    </html>
    

    b.html

    <p>This is my include file</p>
    

    这个方法是解决我的问题的简单而干净的解决方案 .

    jQuery .load() 文档是here .

  • 6

    作为替代方案,如果您可以访问服务器上的.htaccess文件,则可以添加一个简单的指令,允许在以.html扩展名结尾的文件上解析php .

    RemoveHandler .html
    AddType application/x-httpd-php .php .html
    

    现在您可以使用简单的PHP脚本来包含其他文件,例如:

    <?php include('b.html'); ?>
    
  • 107

    Here is a great article,您可以实现公共库,只需使用下面的代码即可在一行中导入任何HTML文件 .

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

    你也可以试试Google Polymer

  • 594

    大多数解决方案都有效,但它们与 jquery 有问题:

    问题是以下代码 $(document).ready(function () { alert($("#includedContent").text()); } 提醒任何内容而不是警告包含的内容 .

    我编写以下代码,在我的解决方案中,您可以访问 $(document).ready 函数中包含的内容:

    (关键是同步加载包含的内容) .

    index.htm

    <html>
        <head>
            <script src="jquery.js"></script>
    
            <script>
                (function ($) {
                    $.include = function (url) {
                        $.ajax({
                            url: url,
                            async: false,
                            success: function (result) {
                                document.write(result);
                            }
                        });
                    };
                }(jQuery));
            </script>
    
            <script>
                $(document).ready(function () {
                    alert($("#test").text());
                });
            </script>
        </head>
    
        <body>
            <script>$.include("include.inc");</script>
        </body>
    
    </html>
    

    include.inc

    <div id="test">
        There is no issue between this solution and jquery.
    </div>
    

    jquery include plugin on github

  • 5

    一个简单的服务器端包含指令,以包含在同一文件夹中找到的另一个文件,如下所示:

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

    Athari的答案(第一个!)太确定了!很好!

    但如果你想 pass the name of the page to be included as URL parameter ,这篇文章有一个很好的解决方案,可以结合使用:

    http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html

    所以它变成这样:

    你的网址:

    www.yoursite.com/a.html?p=b.html
    

    a.html 代码现在变为:

    <html> 
      <head> 
        <script src="jquery.js"></script> 
        <script> 
        function GetURLParameter(sParam)
        {
          var sPageURL = window.location.search.substring(1);
          var sURLVariables = sPageURL.split('&');
          for (var i = 0; i < sURLVariables.length; i++) 
          {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) 
            {
                return sParameterName[1];
            }
          }
        }​
        $(function(){
          var pinc = GetURLParameter('p');
          $("#includedContent").load(pinc); 
        });
        </script> 
      </head> 
    
      <body> 
         <div id="includedContent"></div>
      </body> 
    </html>
    

    它非常适合我!我希望有帮助:)

  • 33

    PHP是一种服务器级脚本语言 . 它可以做很多事情,但一种流行的用法是在页面中包含HTML文档,与SSI非常相似 . 与SSI一样,这是一种服务器级技术 . 如果您不确定您的网站上是否有PHP功能,请与您的托管服务提供商联系 .

    这是一个简单的PHP脚本,您可以使用它在任何支持PHP的网页上包含一小段HTML:

    将站点的常用元素的HTML保存为单独的文件 . 例如,您的导航部分可能会保存为navigation.html或navigation.php . 使用以下PHP代码在每个页面中包含该HTML .

    <?php require($DOCUMENT_ROOT . "navigation.php"); ?>
    

    在要包含该文件的每个页面上使用相同的代码 . 确保将已突出显示的文件名更改为包含文件的名称和路径 .

  • 0

    不需要脚本 . 没有必要在服务器端做任何花哨的东西(这可能是更好的选择)

    <iframe src="/path/to/file.html" seamless></iframe>
    

    由于旧浏览器不支持无缝,您应该添加一些css来修复它:

    iframe[seamless] {
        border: none;
    }
    

    请记住,对于不支持无缝的浏览器,如果单击iframe中的链接,它将使框架转到该URL,而不是整个窗口 . 解决这个问题的方法是让所有链接都有 target="_parent" ,浏览器支持是"good enough" .

  • 0

    从上面扩展lolo的答案,如果你需要包含很多文件,这里有一点自动化:

    <script>
      $(function(){
        var includes = $('[data-include]');
        jQuery.each(includes, function(){
          var file = 'views/' + $(this).data('include') + '.html';
          $(this).load(file);
        });
      });
    </script>
    

    然后在html中包含一些内容:

    <div data-include="header"></div>
    <div data-include="footer"></div>
    

    其中包括文件views / header.html和views / footer.html

  • 4

    目前没有针对该任务的直接HTML解决方案 . 即使HTML Imports(永久在草稿中)也不会做这件事,因为Import!= Include并且无论如何都需要一些JS魔法 .
    我最近写了a VanillaJS script,它只是将HTML包含在HTML中,没有任何复杂性 .

    只需放入 a.html

    <link data-wi-src="b.html" />
    <!-- ... and somewhere below is ref to the script ... -->
    <script src="wm-html-include.js"> </script>
    

    它是 open-source 并且可以给出一个想法(我希望)

  • -1

    我编写的库的无耻插件解决了这个问题 .

    https://github.com/LexmarkWeb/csi.js

    <div data-include="/path/to/include.html"></div>
    

    以上将采用 /path/to/include.html 的内容并用它替换 div .

  • 5

    这对我有所帮助 . 要将 b.html 中的html代码块添加到 a.html ,这应该进入 a.htmlhead 标记:

    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    

    然后在body标签中,使用唯一的id和javascript块创建一个容器,以将 b.html 加载到容器中,如下所示:

    <div id="b-placeholder">
    
    </div>
    
    <script>
    $(function(){
      $("#b-placeholder").load("b.html");
    });
    </script>
    
  • -6

    一个very old solution我当时确实满足了我的需求,但这里是如何做到符合标准的代码:

    <!--[if IE]>
    <object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
    <p>backup content</p>
    </object>
    <![endif]-->
    
    <!--[if !IE]> <-->
    <object type="text/html" data="some.html">
    <p>backup content</p>
    </object>
    <!--> <![endif]-->
    
  • 3

    使用jquery你需要导入库

    我建议你使用PHP

    <?php
        echo"<html>   
              <body>";
    ?> 
    <?php
        include "b.html";
    ?>
    <?php
        echo" </body> 
            </html>";
    ?>
    

    b.html

    <div>hi this is ur file :3<div>
    
  • 75

    我的解决方案类似于上面的lolo . 但是,我通过JavaScript的document.write插入HTML代码而不是使用jQuery:

    a.html:

    <html> 
      <body>
      <h1>Put your HTML content before insertion of b.js.</h1>
          ...
    
      <script src="b.js"></script>
    
          ...
    
      <p>And whatever content you want afterwards.</p>
      </body>
    </html>
    

    b.js:

    document.write('\
    \
        <h1>Add your HTML code here</h1>\
    \
         <p>Notice however, that you have to escape LF's with a '\', just like\
            demonstrated in this code listing.\
        </p>\
    \
    ');
    

    我反对使用jQuery的原因是jQuery.js的大小约为90kb,我希望尽可能减少加载的数据量 .

    为了在没有太多工作的情况下获取正确转义的JavaScript文件,您可以使用以下sed命令:

    sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
    

    或者只使用下面在Github上作为Gist发布的方便的bash脚本,自动执行所有必要的工作,将 b.html 转换为 b.jshttps://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

    对于改进的sed命令,Greg Minshall的信用也逃脱了反斜杠和单引号,这是我原来的sed命令没有考虑的 .

  • 3

    根据https://stackoverflow.com/a/31837264/4360308的答案,我用Nodejs(express cheerio)实现了这个功能,如下所示:

    HTML (index.html)

    <div class="include" data-include="componentX" data-method="append"></div>
    <div class="include" data-include="componentX" data-method="replace"></div>
    

    JS

    function includeComponents($) {
        $('.include').each(function () {
            var file = 'view/html/component/' + $(this).data('include') + '.html';
            var dataComp = fs.readFileSync(file);
            var htmlComp = dataComp.toString();
            if ($(this).data('method') == "replace") {
                $(this).replaceWith(htmlComp);
            } else if ($(this).data('method') == "append") {
                $(this).append(htmlComp);
            }
        })
    }
    
    function foo(){
        fs.readFile('./view/html/index.html', function (err, data) {
            if (err) throw err;
            var html = data.toString();
            var $ = cheerio.load(html);
            includeComponents($);
            ...
        }
    }
    

    append - >将内容包含在div中

    replace - >替换div

    您可以根据相同的设计轻松添加更多行为

  • 6

    您可以使用HTML Imports(https://www.html5rocks.com/en/tutorials/webcomponents/imports/)的polyfill,或者简化的解决方案https://github.com/dsheiko/html-import

    例如,在页面上导入HTML块,如下所示:

    <link rel="html-import" href="./some-path/block.html" >
    

    该块可能有自己的导入:

    <link rel="html-import" href="./some-other-path/other-block.html" >
    

    导入器将指令替换为加载的HTML,与SSI非常相似

    加载这个小JavaScript后,这些指令将自动提供:

    <script async src="./src/html-import.js"></script>
    

    当DOM自动准备好时,它将处理导入 . 此外,它还公开了一个可用于手动运行,获取日志等的API . 请享用 :)

  • 8

    我知道这是一个非常古老的帖子,所以当时没有一些方法可用 . 但这是我非常简单的看法(根据Lolo的回答) .

    它依赖于HTML5 data- *属性,因此非常通用,因为它使用jQuery的for-each函数来获取每个.class匹配“load-html”并使用其各自的“data-source”属性来加载内容:

    <div class="container-fluid">
        <div class="load-html" id="NavigationMenu" data-source="header.html"></div>
        <div class="load-html" id="MainBody" data-source="body.html"></div>
        <div class="load-html" id="Footer" data-source="footer.html"></div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script>
    $(function () {
        $(".load-html").each(function () {
            $(this).load(this.dataset.source);
        });
    });
    </script>
    
  • 4

    您可以使用JavaScript的库jQuery执行此操作,如下所示:

    HTML:

    <div class="banner" title="banner.html"></div>
    

    JS:

    $(".banner").each(function(){
        var inc=$(this);
        $.get(inc.attr("title"), function(data){
            inc.replaceWith(data);
        });
    });
    

    请注意, banner.html 应位于您的其他网页所在的同一域下,否则由于Cross-Origin Resource Sharing政策,您的网页将拒绝 banner.html 文件 .

    此外,请注意,如果你加载使用JavaScript的内容,Google将无法为其编制索引,因此对于搜索引擎优化而言,这并不是一个好方法 .

  • 127

    使用 ES6 backticks ``:template literals

    let nick = "Castor", name = "Moon", nuts = 1
    
    more.innerHTML = `
    
    <h1>Hello ${nick} ${name}!</h1>
    
    You collected ${nuts} nuts so far!
    
    <hr>
    
    Double it and get ${nuts + nuts} nuts!!
    
    `
    
    <div id="more"></div>
    

    这样我们就可以包含没有编码引号的html,包含DOM中的变量等等 .

    它是一个功能强大的模板引擎,我们可以使用单独的js文件并使用事件来加载内容,甚至可以将所有内容分块并按需调用:

    let inject = document.createElement('script');
    inject.src= '//....com/template/panel45.js';
    more.appendChild(inject);
    

    https://caniuse.com/#feat=template-literals

  • 2

    结帐HTML5导入via Html5rocks tutorialpolymer-project

    For example:

    <head>
      <link rel="import" href="/path/to/imports/stuff.html">
    </head>
    
  • 7

    在w3.js中包含这样的作品:

    <body>
    <div w3-include-HTML="h1.html"></div>
    <div w3-include-HTML="content.html"></div>
    <script>w3.includeHTML();</script>
    </body>
    

相关问题