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

在JSF中,我可以这样做:

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

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

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


当前回答

这些解决方案都不适合我的需要。我在寻找更像php的东西。在我看来,这个解决方案非常简单有效。

include.js - - - >

void function(script) {
    const { searchParams } = new URL(script.src);
    fetch(searchParams.get('src')).then(r => r.text()).then(content => {
        script.outerHTML = content;
    });
}(document.currentScript);

index . html - - - >

<script src="/include.js?src=/header.html">
<main>
    Hello World!
</main>
<script src="/include.js?src=/footer.html">

可以做一些简单的调整来创建include_once、require和require_once,它们可能都很有用,这取决于您正在做什么。下面是一个简短的例子。

include_once - - - >

var includedCache = includedCache || new Set();
void function(script) {
    const { searchParams } = new URL(script.src);
    const filePath = searchParams.get('src');
    if (!includedCache.has(filePath)) {
        fetch(filePath).then(r => r.text()).then(content => {
            includedCache.add(filePath);
            script.outerHTML = content;
        });
    }
}(document.currentScript);

希望能有所帮助!

其他回答

要让解决方案工作,您需要包括文件csi.min.js,您可以在这里找到它。

根据GitHub上显示的例子,要使用这个库,你必须在你的页头中包含文件csi.js,然后你需要在容器元素上添加data-include属性,将其值设置为你想要包含的文件。

隐藏复制代码

<html>
  <head>
    <script src="csi.js"></script>
  </head>
  <body>
    <div data-include="Test.html"></div>
  </body>
</html>

... 希望能有所帮助。

不需要脚本。不需要做任何花哨的东西服务器端(尽管这可能是一个更好的选择)

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

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

iframe[seamless] {
    border: none;
}

请记住,对于不支持无缝链接的浏览器,如果您单击iframe中的链接,它将使框架指向该url,而不是整个窗口。一种解决方法是让所有链接都有target="_parent",尽管浏览器的支持是“足够好”。

这对我很有帮助。为了将一个html代码块从b.html添加到a.html,这应该放在a.html的head标签中:

<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>

以下工作,如果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

扩展lolo的回答,如果您必须包含很多文件,这里有更多的自动化。使用下面的JS代码:

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

然后在html中包含一些东西:

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

这将包括文件views/header.html和views/footer.html。