我有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文件中做到这一点?
当前回答
大多数解决方案的工作,但他们有jquery的问题:
问题出现在代码$(document)下面。ready(function () {alert($("#includedContent").text());}不提示任何内容,而不是提示包含的内容。
我写下面的代码,在我的解决方案中,你可以访问包含在$(文档)的内容。现成的函数:
(关键是同步加载所包含的内容)。
你可以:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
include.inc:
<div id="test">
There is no issue between this solution and jquery.
</div>
Jquery包含在github插件
其他回答
不要脸的插头一个库,我写了解这个。
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
上面的代码将获取/path/to/include.html的内容,并用它替换div。
作为一种替代方法,如果你可以访问服务器上的。htaccess文件,你可以添加一个简单的指令,允许php在以。html扩展名结尾的文件上被解释。
RemoveHandler .html
AddType application/x-httpd-php .php .html
现在你可以使用一个简单的php脚本来包含其他文件,比如:
<?php include('b.html'); ?>
下面是我使用Fetch API和async函数的方法
<div class="js-component" data-name="header" data-ext="html"></div>
<div class="js-component" data-name="footer" data-ext="html"></div>
<script>
const components = document.querySelectorAll('.js-component')
const loadComponent = async c => {
const { name, ext } = c.dataset
const response = await fetch(`${name}.${ext}`)
const html = await response.text()
c.innerHTML = html
}
[...components].forEach(loadComponent)
</script>
在我看来,最好的解决方案使用jQuery:
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p>This is my include file</p>
这个方法简单明了地解决了我的问题。
jQuery .load()文档在这里。
大多数解决方案的工作,但他们有jquery的问题:
问题出现在代码$(document)下面。ready(function () {alert($("#includedContent").text());}不提示任何内容,而不是提示包含的内容。
我写下面的代码,在我的解决方案中,你可以访问包含在$(文档)的内容。现成的函数:
(关键是同步加载所包含的内容)。
你可以:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
include.inc:
<div id="test">
There is no issue between this solution and jquery.
</div>
Jquery包含在github插件