我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.html文件中做到这一点?
我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.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。
其他回答
以下工作,如果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
一个简单的服务器端包含指令,包括在同一文件夹中找到的另一个文件,如下所示:
<!--#include virtual="a.html" -->
你也可以试试:
<!--#include file="a.html" -->
我强烈建议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中获取。
在w3.js中include是这样工作的:
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
要获得正确的描述,请查看这个:https://www.w3schools.com/howto/howto_html_include.asp
Web组件
我创建了以下类似JSF的web组件
<ui-include src="b.xhtml"><ui-include>
你可以在你的页面中使用它作为常规的html标签(在包括snippet js代码之后)
customElements.define('ui-include', class extends HTMLElement { async connectedCallback() { let src = this.getAttribute('src'); this.innerHTML = await (await fetch(src)).text();; } }) ui-include { margin: 20px } /* example CSS */ <ui-include src="https://cors-anywhere.herokuapp.com/https://example.com/index.html"></ui-include> <div>My page data... - in this snippet styles overlaps...</div> <ui-include src="https://cors-anywhere.herokuapp.com/https://www.w3.org/index.html"></ui-include>