我有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文件中做到这一点?
当前回答
我强烈建议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
不需要脚本。不需要做任何花哨的东西服务器端(尽管这可能是一个更好的选择)
<iframe src="/path/to/file.html" seamless></iframe>
由于旧的浏览器不支持无缝,你应该添加一些css来修复它:
iframe[seamless] {
border: none;
}
请记住,对于不支持无缝链接的浏览器,如果您单击iframe中的链接,它将使框架指向该url,而不是整个窗口。一种解决方法是让所有链接都有target="_parent",尽管浏览器的支持是“足够好”。
您可以使用HTML Imports的填充(https://www.html5rocks.com/en/tutorials/webcomponents/imports/)或简化的解决方案 https://github.com/dsheiko/html-import
例如,在你导入HTML块的页面上:
<link rel="html-import" href="./some-path/block.html" >
该块可以有自己的导入:
<link rel="html-import" href="./some-other-path/other-block.html" >
导入器用加载的HTML替换指令,就像SSI一样
这些指令将在你加载这个小JavaScript时自动提供:
<script async src="./src/html-import.js"></script>
它将在DOM准备就绪时自动处理导入。此外,它还公开了一个API,您可以使用该API手动运行、获取日志等等。享受:)
这对我很有帮助。为了将一个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>
我知道这是一个非常老的帖子,所以一些方法在当时是不可用的。 但以下是我对它的简单看法(基于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>