通过 JavaScript 或 jquery 在 HTML 中动态包含文件

2022-01-25 00:00:00 file include jquery javascript html

I tried the following code. But it doesn't work properly. Only one file add/ include repetitively. How can I solve this? **I want to create a custom tag "" which can INCLUDE html file!!!! –

var createIncludeTag = document.createElement('include');
$(function(){
    var includeFile = $('include').attr('href');
    $("include").load(includeFile);		   
});

<include href="nav.html"></include>
<include href="main.html"></include>
<include href="footer.html"></include>

解决方案

<include> is not a valid html element.

You can use <link> element with rel attribute set to "import" to load resources into document. At load event of <link> element you can get the content of resource using link.import

<link rel="import" href="nav.html" type="text/html">

   $(function() {
     $("body").append($("link[href='nav.html']")[0].import.body.innerHTML)
   })

   $("link[href='nav.html']").on("load", function() {
     $("body").append(this.import.body.innerHTML)
   })

Alternatively, you can use .load()

   $("#element").load("nav.html");

相关文章