我的网站在每个页面上都有相同的导航菜单,我是否可以像使用CSS那样链接到第二个HTML文件(包含导航HTML代码),而不是为每个页面重写HTML代码?这样做会带来问题吗?
我的网站在每个页面上都有相同的导航菜单,我是否可以像使用CSS那样链接到第二个HTML文件(包含导航HTML代码),而不是为每个页面重写HTML代码?这样做会带来问题吗?
load
函数加载此文件至HTML代码中。$("#headerDiv").load("header.html")
请注意,这将需要一个Web服务器,因为load函数会向服务器发送请求。
查看代码示例:
demo.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function(){
$("#headerDiv").load("header.html");
});
</script>
</head>
<body>
<div id="headerDiv"></div>
<!-- Rest of the code -->
</body>
</html>
header.html
<div >
<a>something</a>
<a>something</a>
</div>
<div w3-include-html="content.html"></div>
相比有什么不同?哪个更好? - dyllandry对于一个HTML解决方案 - 因为您的问题中没有其他标签 - 可以使用HTML导入:
<link rel="import" href="nav.html">
但是这个新的 -工作草案- 并没有很好的浏览器支持。
资源:
<?php include_once('includes/sidebar.php'); ?>
,使用 AngularJS 可以这样实现 <div ng-include="'includes/navbar.html'"></div>
ng-include
示例 - Mi-Creativity<div w3-include-HTML="content.html">My HTML include will go here.</div>
<script>
(function () {
myHTMLInclude();
function myHTMLInclude() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
myHTMLInclude();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
})();
</script>
注意事项
HTML没有简单的包含机制(除了像iframe这样具有副作用的框架)。
更好的解决方案是使用服务器端包含,这是向文档添加常见部分的首选方式,当然是在服务器上进行。
<script src="w3-include-HTML.js"></script>
这样的? - Mi-CreativityW3schools 有一个 include。另外,他们也拥有自己的 CSS。在页脚中放置调用(无论何处)。
<script src="vendor/w3js.min.js"></script>
<script src="w3.includeHTML();"></script>
然后在页面上:
<header class="header navbar-fixed-top">
<nav id="inc_nav" w3-include-html="nav.html"></nav>
</header>
<section id="inc_header" w3-include-html="header.html"></section>
<div id="content" tabindex="-1"></div>