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

在JSF中,我可以这样做:

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

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

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


当前回答

你试过iFrame注入吗?

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

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

问候

其他回答

使用ES6反撇号' ':模板文字!

let nick = "Castor", name = "Moon", nuts = 1 更多。innerHTML = ' <h1>Hello ${nick} ${name}!< / h1 > 到目前为止你收集了${nuts} nuts ! <人力资源> 加倍就能得到${坚果+坚果}坚果!! ` < div id = "更多" > < / div >

通过这种方式,我们可以在不编码引号的情况下包含html,包括来自DOM的变量,等等。

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

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

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

作为一种替代方法,如果你可以访问服务器上的。htaccess文件,你可以添加一个简单的指令,允许php在以。html扩展名结尾的文件上被解释。

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

现在你可以使用一个简单的php脚本来包含其他文件,比如:

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

我知道这是一个非常老的帖子,所以一些方法在当时是不可用的。 但以下是我对它的简单看法(基于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>

在我看来,最好的解决方案使用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()文档在这里。

使用jquery你需要导入库

我建议您使用PHP

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

b.html

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