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

在JSF中,我可以这样做:

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

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

我们如何在*.html文件中做到这一点?


当前回答

另一种方法是使用Fetch API和Promise

<html>
 <body>
  <div class="root" data-content="partial.html">
  <script>
      const root = document.querySelector('.root')
      const link = root.dataset.content;

      fetch(link)
        .then(function (response) {
          return response.text();
        })
        .then(function (html) {
          root.innerHTML = html;
        });
  </script>
 </body>
</html>

其他回答

我的解决方案类似于上面的lolo。但是,我通过JavaScript的文档插入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>

研究:

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

或者只是使用以下方便的bash脚本作为Github上的Gist发布,它自动完成所有必要的工作,将b.html转换为b.js: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6

感谢Greg Minshall改进的sed命令,它还转义了反斜杠和单引号,这是我最初的sed命令没有考虑到的。

另外,对于支持模板字面量的浏览器,以下方法也适用:

研究:

document.write(`

    <h1>Add your HTML code here</h1>

     <p>Notice, you do not have to escape LF's with a '\',
        like demonstrated in the above code listing.
    </p>

`);

你试过iFrame注入吗?

它在文档中注入iFrame并删除自己(它应该在HTML DOM中)

<iframe src=“header.html” onload=“this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()”></iframe>

问候

我知道这是一个非常老的帖子,所以一些方法在当时是不可用的。 但以下是我对它的简单看法(基于Lolo的回答)。

它依赖于HTML5的data-*属性,因此非常通用,因为它使用jQuery的for-each函数来获取每个匹配“load-html”的.class,并使用其各自的“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>

插入指定文件的内容。

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

这是我的内联解决方案:

(() => { const includes = document.getElementsByTagName('include'); [] .forEach。调用(包含I => { let filePath = i.getAttribute('src'); fetch (filePath)。然后(file => { file.text()。然后(content => { i.insertAdjacentHTML(“afterend”、内容); i.remove (); }); }); }); }) (); FOO < p > < / p > <包括src = " a.html " >加载…< /包括> 酒吧< p > < / p > <包括src = " b.html " >加载…< /包括> < p > t < / p >