/*
表格排序功能
事件:2012 7 24
DOM 节点
如果表格需要排序 在表格属性中添加 sort="true"
并且 id是唯一并且是必须的
此js文件直接引入即可
因为制作的仓储 没有注释
ID|-
|
name|-
|
1 |
开心 |
3 |
开饭 |
5 |
开放 |
*/
var Core = (function(window){
return {
init: function(){
Core.getTableById();
Core.setHeadClick();
},
I: function(id){
return document.getElementById(id);
},
N: function(name){
return document.getElementsByTagName(name);
},
config: {
arr:[]
},
getTableById: function(){
var table_arr=Core.N("table");
for(var i = 0; i if(table_arr[i].getAttribute("sort")){
Core.config.arr.push(table_arr[i].getAttribute("id"));
}
}
//alert(Core.config.arr)
},
setHeadClick: function(){
var arr = Core.config.arr;
if(!arr.length) return false;
for(var j = 0 ; jvar thead = Core.I(arr[j]).getElementsByTagName("thead")[0].getElementsByTagName("td");
for(var i = 0; i
if(thead[i].attachEvent){
thead[i].attachEvent("onclick",Core.sortList)
}else{
thead[i].addEventListener("click",Core.sortList,false)
}
//if(i==0){
// thead[i].click();
// }
}
}
},
sortList: function(e){
var index=0,arr=[],sort="asc",table=null;
if(e.srcElement){
index=e.srcElement.cellIndex;
sort=e.srcElement.getAttribute("sort");
e.srcElement.className=sort == "asc" ? "desc" : "asc";
e.srcElement.setAttribute("sort", sort == "asc" ? "desc" : "asc");
table = Core.getTableId(e.srcElement)
}else{
index=e.currentTarget.cellIndex;
sort=e.currentTarget.getAttribute("sort");
e.currentTarget.className=sort == "asc" ? "desc" : "asc";
e.currentTarget.setAttribute("sort", sort == "asc" ? "desc" : "asc");
table = Core.getTableId(e.currentTarget)
}
Core.getList(table,index,arr);
Core.updateList(table,sort,arr);
},
getTableId: function(p){
for(var i=0,n=p;n=n.parentNode;i++){
if(i>100) break;
if(n.nodeName=="TABLE"){
//alert(n.nodeName/*n.getAttribute("id")*/)
return n;
}
}
},
getList: function (table,index,arr){
var table = table.getElementsByTagName("tbody")[0];
for(var i = 0; ivar item = table.rows[i];
for(var j = 0; jvar jtem = item.cells[index];
if(jtem.innerHTML){
//alert(jtem.innerHTML)
arr[i]=jtem.innerHTML;
}
break;
}
}
},
updateList: function (table,sort,arr){
var table = table.getElementsByTagName("tbody")[0];
for(var i = 0; ifor(var j = i+1;jif(sort=="asc"){
if(arr[i] > arr[j]){
var rwos=table.rows[i].cloneNode(true);
table.replaceChild(table.rows[j],table.rows[i]);
if(j+1==arr.length){
//table.insertBefore(rwos,null);
table.appendChild(rwos)
}else{
table.insertBefore(rwos,table.rows[j]);
}
var tim= arr[i];
arr.splice(i,1,arr[j]);
arr.splice(j,1,tim);
}
}else{
if(arr[i] var rwos=table.rows[i].cloneNode(true);
table.replaceChild(table.rows[j],table.rows[i]);
if(j+1==arr.length){
//table.insertBefore(rwos,null);
table.appendChild(rwos)
}else{
table.insertBefore(rwos,table.rows[j]);
}
var tim= arr[i];
arr.splice(i,1,arr[j]);
arr.splice(j,1,tim);
}
}
}
}
}
};
})(window);
window.onload=Core.init;