我有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文件中做到这一点?
当前回答
使用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
其他回答
在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
您可以使用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手动运行、获取日志等等。享受:)
我知道这是一个非常老的帖子,所以一些方法在当时是不可用的。 但以下是我对它的简单看法(基于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>
以下工作,如果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
我还有一个解
在javascript中使用Ajax
以下是Github repo中的解释代码 https://github.com/dupinder/staticHTML-Include
基本思想是:
index . html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='main.js'></script>
</head>
<body>
<header></header>
<footer></footer>
</body>
</html>
main.js
fetch("./header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});