我有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文件中做到这一点?
当前回答
使用includeHTML(最小js-lib:约150行)
通过HTML标签加载HTML部件(纯js) 支持加载:异步/同步,任何深度递归包括
支持的协议:http://, https://,文件:/// 支持的浏览器:IE 9+, FF, Chrome(也可能是其他)
用法:
1.在HTML文件中插入includeHTML到头部部分(或在正文结束标记之前):
<script src="js/includeHTML.js"></script>
2.在任何地方使用includeHTML作为HTML标签:
<div data-src="header.html"></div>
其他回答
使用ES6反撇号' ':模板文字!
let nick = "Castor", name = "Moon", nuts = 1 更多。innerHTML = ' <h1>Hello ${nick} ${name}!< / h1 > 到目前为止你收集了${nuts} nuts ! <人力资源> 加倍就能得到${坚果+坚果}坚果!! ` < div id = "更多" > < / div >
通过这种方式,我们可以在不编码引号的情况下包含html,包括来自DOM的变量,等等。
它是一个强大的模板引擎,我们可以使用单独的js文件和使用事件来加载内容,甚至将所有内容分成块并按需调用:
let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);
https://caniuse.com/#feat=template-literals
插入指定文件的内容。
<!--#include virtual="filename.htm"-->
大多数解决方案的工作,但他们有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://stackoverflow.com/a/31837264/4360308的回答 我用Nodejs (+ express + cheerio)实现了这个功能,如下所示:
HTML (index . HTML)
<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>
JS
function includeComponents($) {
$('.include').each(function () {
var file = 'view/html/component/' + $(this).data('include') + '.html';
var dataComp = fs.readFileSync(file);
var htmlComp = dataComp.toString();
if ($(this).data('method') == "replace") {
$(this).replaceWith(htmlComp);
} else if ($(this).data('method') == "append") {
$(this).append(htmlComp);
}
})
}
function foo(){
fs.readFile('./view/html/index.html', function (err, data) {
if (err) throw err;
var html = data.toString();
var $ = cheerio.load(html);
includeComponents($);
...
}
}
Append ->将内容包含到div中
Replace ->替换div
您可以根据相同的设计轻松添加更多的行为
你可以用JavaScript的jQuery库来实现这一点,就像这样:
HTML:
<div class="banner" title="banner.html"></div>
JS:
$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});
请注意banner.html应该位于您的其他页面所在的相同域下,否则您的网页将拒绝banner.html文件,因为跨源资源共享政策。
另外,请注意,如果您使用JavaScript加载内容,谷歌将无法对其进行索引,因此对于SEO而言,这并不是一个好方法。