[英]Include file In HTML by JavaScript or jquery dynamically
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!!!!
**我想创建一个自定义标签“”,它可以包含 html 文件!!!! –
——
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. <include>
不是有效的html
元素。
You can use <link>
element with rel
attribute set to "import"
to load resources into document
.您可以使用
rel
属性设置为"import"
<link>
元素将资源加载到document
。 At load
event of <link>
element you can get the content of resource using link.import
在
<link>
元素的load
事件中,您可以使用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()
或者,您可以使用
.load()
$("#element").load("nav.html");
According to jquery API reference of .attr() function根据.attr() 函数的 jquery API 参考
Description : Get the value of an attribute for the first element in the set of matched elements.
描述:获取匹配元素集中第一个元素的属性值。
That's why you only get the first include html loaded for all three elements.这就是为什么您只为所有三个元素加载第一个包含 html。
You have to use .each() function instead.您必须改用.each()函数。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function () {
$("include").each(function (index, value) {
$(this).load($(this).attr("href"));
});
});
</script>
</head>
<body>
<include href="nav.html"></include>
<include href="main.html"></include>
<include href="footer.html"></include>
</body>
</html>
By the way, creating a custom <include> TAG might not be a good idea.顺便说一句,创建自定义 <include> 标签可能不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.