ajax方式表格插入和更新
/**
* 根据json串更新表格的内容
*/
function insert(data){
var rowobjs = data.items;
if(rowobjs){
//获取表的字段
var keys = new Array();
var k=0,len=rowobjs.length;
for(var key in rowobjs[0]){
keys[k] = key;
k++;
}
//构建每一行的内容
for(var i=0;i<len;i++){
//构造表模式
var tr_pattern = $('.table_con_div tbody tr').eq(0).clone();
var cols = tr_pattern.children().length;
//根据模式插入
if(i==0){
//删除所有表单元格
$('.table_con_div tr:not(:first)').remove();
tr_pattern.insertAfter($('.table_con_div tbody tr:first'));//不存在表记录
$('.table_con_div tr:first').remove();
$('.table_con_div tr:first').removeAttr('style');
}else{
tr_pattern.insertAfter($('.table_con_div tbody tr:last'));//存在表记录
}
//修改插入的内容
var tds = $('.table_con_div tbody tr').eq(i).children();
for(var j=0;j<cols;j++){
if(j == 0){
$(tds[0]).children().val(rowobjs[i][keys[0]]);
}else if(j==1){
$(tds[1]).html(i+1);
}else{
$(tds[j]).html(rowobjs[i][keys[j-1]]);
}
}
}
}
$('.table_con_div tbody tr').each(function(i,item){
$(this).removeClass();
if(i%2 == 0){
$(this).addClass('tr_mouseout');
}else{
$(this).addClass('tr_grey');
}
});
replaceEmpty();
mouseEffect();
}
//替换表格中的空记录
function replaceEmpty(){
$('.table_con_div tbody td').each(function(i,item){
if($(item).html() == '' || $(item).html() == '0'){
$(item).html('--');
}
});
}
function mouseEffect(document){
document = document || window.document;
var classname = '';
$(".table_con_div tbody tr:not(:first)",document).mouseover(function(e){
classname = $(this).attr('class');
$(this).removeClass();
$(this).addClass('tr_mouseover');
}).mouseout(function(e){
$(this).removeClass();
$(this).addClass(classname);
classname = '';
});
}
/**
* 序号重新排列
*/
function sort(){
var $rowobj = $('.table_con_div tbody tr:not(:first)');
var len = $rowobj.length;
$rowobj.each(function(i,v){
$(this).removeClass();
if(i % 2 == 0){
$(this).addClass("tr_mouseout");
}else{
$(this).addClass("tr_grey");
}
$(this).children().eq(1).html(i+1);
});
}