对象右自己的属性和方法,将标签tr td 可以看作是一个对象 innerHTML可以看作是他们的方法
按照层级关系,table->thead>tr>td 看到这里大概也知道了tabel元素的层级关系。
实例代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table id="table" border="1" cellspacing="0" cellpadding="0" width="500">
<!-- <tr><th>Header</th></tr>
<tr><td>Data</td></tr> -->
</table>
</body>
<script>
//数据
var datas=[
{name:'小红',age:12,num:25,score:123},
{name:'小民',age:11,num:24,score:123},
{name:'小陶',age:16,num:22,score:123},
{name:'小哎',age:11,num:26,score:123},
{name:'小帨',age:12,num:21,score:123},
{name:'小新',age:17,num:2,score:123},
{name:'小率',age:13,num:15,score:123},
{name:'小雄',age:12,num:12,score:123},
]
//改造
function TableSort(id,tdatas){
this.ctn = document.getElementById(id);
this.tdatas = tdatas;
}
TableSort.prototype.init=function(){
//初始化标题
var thead = this.initTile();
//初始化数据
var tbody = this.initThbodyData(this.tdatas);
this.ctn.appendChild(thead);
this.ctn.appendChild(tbody);
//绑定事件
this.addEvent(this.tdatas);
}
//1.初始化主题
TableSort.prototype.initTile=function(){
var theader = document.createElement('thead');
var tag = "<tr>"+
"<th type='name'>姓名</th>"+
"<th type='age'>年龄</th>"+
"<th type='num'>学号</th>"+
"<th type='score'>分数</th>"
+"</tr>"
theader.innerHTML=tag;
return theader;
}
//2.初始化数据
TableSort.prototype.initThbodyData=function(tdatas){
var thbody = document.createElement('tbody');
var tags = [];
for(var i=0;i<tdatas.length;i++){
var tag = "<tr>"+
"<td>"+tdatas[i].name+"</td>"+
"<td>"+tdatas[i].age+"</td>"+
"<td>"+tdatas[i].num+"</td>"+
"<td>"+tdatas[i].score+"</td>"
+"</tr>"
tags.push(tag);
}
for(var i=0;i<tags.length;i++){
thbody.innerHTML+=tags[i];
}
return thbody;
}
//4.为标题创建点击事件
TableSort.prototype.addEvent=function(tdatas){
var that = this;
var ths = document.getElementsByTagName('th');
for(var i=0;i<ths.length;i++){
ths[i].onclick=function(){
var sortName = this.getAttribute('type'); //获取自定义属性
this.flag=this.flag==-1?1:-1;
var _this=this;
tdatas.sort(function(o1,o2){
var n1=o1[sortName];
var n2 =o2[sortName];
if(n1>n2){
return _this.flag;
}else if(n1<n2){
return -_this.flag;
}else{
return 0;
}
});
var newTbody = that.initThbodyData(tdatas); //initThbodyData是that的方法
var oldTbody = document.getElementsByTagName('tbody')[0];
that.ctn.replaceChild(newTbody,oldTbody); //替换新的子类 这里调用的是ctn 不是this
};
}
}
//调用函数
var ts = new TableSort('table',datas);
ts.init();
</script>
</html>