平時(shí)在html中,我們通常將項(xiàng)目公共部分如 header 、footer、menu等獨(dú)立封裝,而不是每個(gè)頁(yè)面都去copy相同的代碼,本次將介紹純html靜態(tài)項(xiàng)目中如何采用include方式引入公共部分頁(yè)面
1、利用jquery的get方法 獲取頁(yè)面后將返回值添加給dom標(biāo)簽,如下:
$.get('header.html',function(data){
$("#header").html(data)
})
利用http請(qǐng)求公共頁(yè)面文件,http response將返回頁(yè)面代碼,然后在通過(guò)html方法動(dòng)態(tài)將代碼添加到指定節(jié)點(diǎn)。
2、第二種方式: 采用h5的w3-include-html 屬性 + js 方法通過(guò)實(shí)現(xiàn)
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
</html>