我有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文件中做到这一点?
当前回答
阿塔里人的回答(第一个!)太有定论了!很好!
但是如果你想要传递页面的名称作为URL参数,这篇文章有一个非常好的解决方案,可以结合使用:
http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
所以它变成了这样:
你的网址:
www.yoursite.com/a.html?p=b.html
a.html代码现在变成:
<html>
<head>
<script src="jquery.js"></script>
<script>
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
$(function(){
var pinc = GetURLParameter('p');
$("#includedContent").load(pinc);
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
这对我来说非常有效! 我希望能有所帮助:)
其他回答
使用jquery你需要导入库
我建议您使用PHP
<?php
echo"<html>
<body>";
?>
<?php
include "b.html";
?>
<?php
echo" </body>
</html>";
?>
b.html
<div>hi this is ur file :3<div>
如果你使用一些框架,比如django/bootle,他们通常会提供一些模板引擎。 假设您使用了bottle,默认的模板引擎是SimpleTemplate engine。 下面是纯html文件
$ cat footer.tpl
<hr> <footer> <p>© stackoverflow, inc 2015</p> </footer>
你可以包括页脚。TPL在你的主文件中,比如:
$ cat dashboard.tpl
%include footer
除此之外,您还可以将参数传递给dashboard .tpl。
我强烈建议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中获取。
一个简单的服务器端包含指令,包括在同一文件夹中找到的另一个文件,如下所示:
<!--#include virtual="a.html" -->
你也可以试试:
<!--#include file="a.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);
希望能有所帮助!