通过 JavaScript 或 jquery 在 HTML 中动态包含文件 [英] Include file In HTML by JavaScript or jquery dynamically

查看:33
本文介绍了通过 JavaScript 或 jquery 在 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");

这篇关于通过 JavaScript 或 jquery 在 HTML 中动态包含文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆