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

在JSF中,我可以这样做:

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

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

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


当前回答

目前还没有针对该任务的直接HTML解决方案。即使是HTML导入(这是永久的草案)也不会做这件事,因为Import != Include和一些JS魔法无论如何都是需要的。 我最近写了一个VanillaJS脚本,它只是为了将HTML包含到HTML中,没有任何复杂性。

只要放在你的。html中

<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>  

它是开源的,可能会给你一个想法(我希望)

其他回答

使用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>
<head>   
    <title>pagetitle</title>
</head>

<frameset rows="*" framespacing="0" border="0" frameborder="no" frameborder="0">
    <frame name="includeName" src="yourfileinclude.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0">   
</frameset>

</html>

仅使用HTML是不可能将HTML文件包含在另一个HTML文件中。这里有一个很简单的方法。使用这个JS库你可以很容易地做到这一点。只需使用以下代码:

<script> include('path/to/file.html', document.currentScript) </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()文档在这里。