Hap*_*ays 16 html javascript jquery include
我有一个html"head"模板和一个导航模板,我希望将其包含在我网站的所有其他html文件中.我发现这篇文章:
我的问题是......如果它是我要包含的标题怎么办?
例如,我有以下文件结构:
/var/www/includes/templates/header.html
navigation.html
Run Code Online (Sandbox Code Playgroud)
header.html可能如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Test Portal</title>
</head>
Run Code Online (Sandbox Code Playgroud)
在这样的情况下,我是否仍然可以按照其他帖子中的示例创建div并通过jquery填充div?
Pun*_*jar 25
我认为使用jQuery将html内容/文件包含到另一个html文件中是最好的方法.
您可以简单地包含jQuery.js并使用加载HTML文件 $("#DivContent").load("yourFile.html");
例如
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#DivContent").load("another_file.html");
});
</script>
</head>
<body>
<div id="DivContent"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
没有这样的标签可用于包含该文件但是有一些第三方方法可用.
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="content.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
有些人也用过
<!--#include virtual="a.html" -->
Run Code Online (Sandbox Code Playgroud)
Rit*_*kar 11
使用<object>标签:
<object data="filename.html"></object>
Run Code Online (Sandbox Code Playgroud)
小智 6
我需要包含许多文件。所以我创建了以下脚本:
<script>
$(function(){
$('[id$="-include"]').each(function (e){
$(this).load("includes\\" + $(this).attr("id").replace("-include", "") + ".html");
});
});
</script>Run Code Online (Sandbox Code Playgroud)
例如,使用 div 为插入放置一个占位符。
<div id="example-include"></div>Run Code Online (Sandbox Code Playgroud)
为我需要包含的所有文件创建文件夹“包含”。创建文件“example.html”。它适用于任意数量的包含。您只需要使用命名约定并将所有包含的文件放在正确的文件夹中。
对于任何对 Web 组件方法感兴趣的人:
<html-include src="my-html.html"></html-include>
Run Code Online (Sandbox Code Playgroud)
以及对应的JS:
class HTMLInclude extends HTMLElement {
constructor() {
super();
this.innerHTML = "Loading...";
this.loadContent();
}
async loadContent() {
const source = this.getAttribute("src");
if (!source) {
throw new Error("No src attribute given.");
}
const response = await fetch(source);
if (response.status !== 200) {
throw new Error(`Could not load resource: ${source}`);
}
const content = await response.text();
this.innerHTML = content;
}
}
window.customElements.define("html-include", HTMLInclude);
Run Code Online (Sandbox Code Playgroud)
请注意,可以使用影子 DOM 做一些好事,以确保加载内容的样式不会影响外部页面。
上面的代码是相当“现代”的 JS,你可能不想在没有一些 polyfills/babel 转译的情况下直接使用上面的代码。