我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。

在JSF中,我可以这样做:

<ui:include src="b.xhtml" />

这意味着在.xhtml文件中,我可以包含b.xhtml。

我们如何在*.html文件中做到这一点?


当前回答

我还有一个解

在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;
  });

其他回答

在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

PHP是一种服务器级脚本语言。它可以做很多事情,但一个流行的用途是在页面中包含HTML文档,这与SSI非常相似。与SSI一样,这是一种服务器级技术。如果你不确定你的网站上是否有PHP功能,请联系你的主机提供商。

下面是一个简单的PHP脚本,你可以使用它在任何支持PHP的网页上包含HTML片段:

将网站常用元素的HTML保存到单独的文件中。例如,导航部分可以保存为navigation.html或navigation.php。 使用下面的PHP代码将该HTML包含在每个页面中。

<?php require($DOCUMENT_ROOT . "navigation.php"); ?>

在希望包含该文件的每个页面上使用相同的代码。 确保将突出显示的文件名更改为包含文件的名称和路径。

你试过iFrame注入吗?

它在文档中注入iFrame并删除自己(它应该在HTML DOM中)

<iframe src=“header.html” onload=“this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()”></iframe>

问候

使用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

这对我很有帮助。为了将一个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>