工作需要写了一个表格的过虑类,使用了mootools.js.
Code
filtertable = {
init:function(){
if (arguments.callee.done) {return;}
arguments.callee.done = true;
$each($(document.body).getElements('table.filterable'), function(table, index) {filtertable.makeFilterable(table);});
},
makeFilterable:function(table){
var tHead = table.getElement('thead');
var tBody = table.getElement('tbody');
if (tHead.rows.length === 0) {return;}
if (tBody.rows.length === 0) {return;}
var headrow = (tHead.rows.length > 1 ? tHead.rows[1].cells : tHead.rows[0].cells);
var filters = new Hash();
$each(headrow, function(cell, index){
var filter = $(cell).getElement('select.filter');
if(filter){
filters.set(index, {'filter':filter, 'cellIndex':index});
}
});
filters.each(function(data, key){
data.filter.addEvent('change', filtertable.filterChange.pass(data.cellIndex, {'filters':filters, 'table': table, 'tHead': tHead, 'tBody': tBody}));
});
},
filterChange:function(cellIndex){
var filters = this.filters.getValues();
var tBody = this.tBody;
var rows = tBody.rows;
$each(rows, function(row){
var hide = false;
for(var i=0; i<filters.length; i++){
var data = filters[i];
if(data.filter.value !== null && data.filter.value !== ''){
if(row.cells[data.cellIndex].innerHTML != data.filter.value){
hide = true;
break;
}
}
}
if(hide) {
$(row).hide();
}else{
$(row).show();
}
hide = false;
});
}
};
window.addEvent('domready', function() {filtertable.init();});
filtertable = {
init:function(){
if (arguments.callee.done) {return;}
arguments.callee.done = true;
$each($(document.body).getElements('table.filterable'), function(table, index) {filtertable.makeFilterable(table);});
},
makeFilterable:function(table){
var tHead = table.getElement('thead');
var tBody = table.getElement('tbody');
if (tHead.rows.length === 0) {return;}
if (tBody.rows.length === 0) {return;}
var headrow = (tHead.rows.length > 1 ? tHead.rows[1].cells : tHead.rows[0].cells);
var filters = new Hash();
$each(headrow, function(cell, index){
var filter = $(cell).getElement('select.filter');
if(filter){
filters.set(index, {'filter':filter, 'cellIndex':index});
}
});
filters.each(function(data, key){
data.filter.addEvent('change', filtertable.filterChange.pass(data.cellIndex, {'filters':filters, 'table': table, 'tHead': tHead, 'tBody': tBody}));
});
},
filterChange:function(cellIndex){
var filters = this.filters.getValues();
var tBody = this.tBody;
var rows = tBody.rows;
$each(rows, function(row){
var hide = false;
for(var i=0; i<filters.length; i++){
var data = filters[i];
if(data.filter.value !== null && data.filter.value !== ''){
if(row.cells[data.cellIndex].innerHTML != data.filter.value){
hide = true;
break;
}
}
}
if(hide) {
$(row).hide();
}else{
$(row).show();
}
hide = false;
});
}
};
window.addEvent('domready', function() {filtertable.init();});