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

在JSF中,我可以这样做:

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

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

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


当前回答

插入指定文件的内容。

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

其他回答

我强烈建议AngularJS的ng-include,不管你的项目是不是AngularJS。

<script src=".../angular.min.js"></script>

<body ng-app="ngApp" ng-controller="ngCtrl">

    <div ng-include="'another.html'"></div> 

    <script>
        var app = angular.module('ngApp', []);
        app.controller('ngCtrl', function() {});
    </script>

</body>

你可以从AngularJS中找到CDN(或下载Zip),更多信息可以从W3Schools中获取。

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

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

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

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

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

扩展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。

这些解决方案都不适合我的需要。我在寻找更像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);

希望能有所帮助!