以引入头页面为例:
头页面:top.html
主页面:index.html
top.html中该怎么写就怎么写,head与body中改写什么还是什么。
index.html中:(路径的问题参考自己的路径,我的是在同一目录下)
另一种方法,我个人觉得还是很好用的:
编写一个include.js
(function(window, document, undefined) {
var Include39485748323 = function() {}
Include39485748323.prototype = {
//倒序循环
forEach: function(array, callback) {
var size = array.length;
for(var i = size - 1; i >= 0; i--){
callback.apply(array[i], [i]);
}
},
getFilePath: function() {
var curWwwPath=window.document.location.href;
var pathName=window.document.location.pathname;
var localhostPaht=curWwwPath.substring(0,curWwwPath.indexOf(pathName));
var projectName=pathName.substring(0,pathName.substr(1).lastIndexOf('/')+1);
return localhostPaht+projectName;
},
//获取文件内容
getFileContent: function(url) {
var ie = navigator.userAgent.indexOf('MSIE') > 0;
var o = ie ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
o.open('get', url, false);
o.send(null);
return o.responseText;
},
parseNode: function(content) {
var objE = document.createElement("div");
objE.innerHTML = content;
return objE.childNodes;
},
executeScript: function(content) {
var mac = /<script>([\s\S]*?)<\/script>/g;
var r = "";
while(r = mac.exec(content)) {
eval(r[1]);
}
},
getHtml: function(content) {
var mac = /<script>([\s\S]*?)<\/script>/g;
content.replace(mac, "");
return content;
},
getPrevCount: function(src) {
var mac = /\.\.\//g;
var count = 0;
while(mac.exec(src)) {
count++;
}
return count;
},
getRequestUrl: function(filePath, src) {
if(/http:\/\//g.test(src)){ return src; }
var prevCount = this.getPrevCount(src);
while(prevCount--) {
filePath = filePath.substring(0,filePath.substr(1).lastIndexOf('/')+1);
}
return filePath + "/"+src.replace(/\.\.\//g, "");
},
replaceIncludeElements: function() {
var $this = this;
var filePath = $this.getFilePath();
var includeTals = document.getElementsByTagName("include");
this.forEach(includeTals, function() {
//拿到路径
var src = this.getAttribute("src");
//拿到文件内容
var content = $this.getFileContent($this.getRequestUrl(filePath, src));
//将文本转换成节点
var parent = this.parentNode;
var includeNodes = $this.parseNode($this.getHtml(content));
var size = includeNodes.length;
for(var i = 0; i < size; i++) {
parent.insertBefore(includeNodes[0], this);
}
//执行文本中的额javascript
$this.executeScript(content);
parent.removeChild(this);
//替换元素 this.parentNode.replaceChild(includeNodes[1], this);
})
}
}
window.onload = function() {
new Include39485748323().replaceIncludeElements();
}
})(window, document)
(路径的问题,自己注意点)
在主页中,在head中加入:
<script src="include.js"></script>
直接可以在body中,加入如下代码:
<include src="top.html"></include>
就可以了。 注意一点,写代码的时候发现的,在要添加的页面(如top.html),只需要显示出来的代码就可以,有的比如说,< head >< body >这些标签可以删一删。存在的时候反而不好。只是暂且记录下,后期修改!
如果哪里有误或不懂,我基本随时在线,评论指出,或者发送邮箱:gaoxinsuc@163.com
一起学习,一起努力,因为我们的时间都不多,尽快成长!