对一个小Table做个转换,需要先将HTML表格数据转成Json以便重新组合输出。于是搜索:HTML->Json,基本上都是找到以下代码:
var keysArr = new Array("key0", "key1","key2");
function TableToJson(tableid) { //tableid是你要转化的表的表名,是一个字符串,如"example"
var rows = document.getElementById(tableid).rows.length; //获得行数(包括thead)
var colums = document.getElementById(tableid).rows[0].cells.length; //获得列数
var json = "[";
var tdValue;
for (var i = 1; i < rows; i++) { //每行
json += "{";
for (var j = 0; j < colums; j++) {
tdName = keysArr[j]; //Json数据的键
json += "\""; //加上一个双引号
json += tdName;
json += "\"";
json += ":";
tdValue = document.getElementById(tableid).rows[i].cells[j].innerHTML;//Json数据的值
if (j === 1) {//第1列是日期格式,需要按照json要求做如下添加
tdValue = "\/Date(" + tdValue + ")\/";
}
json += "\"";
json += tdValue;
json += "\"";
json += ",";
}
json = json.substring(0, json.length - 1);
json += "}";
json += ",";
}
json = json.substring(0, json.length - 1);
json += "]";
return json;
}
代码大体没有什么问题,给出了很好的思路,但有几个不足:
整理后代码如下:
//fieldArray与列对应,做为json的key
var fieldArray = new Array("code", "text","desc","proto");
/*
*tableid是你要转化的表的表名,是一个字符串,如"mytable"
*/
function TableToJson(tableid) {
//获得行数(包括thead)与列数
var rows = document.getElementById(tableid).rows.length;
var columCount = document.getElementById(tableid).rows[0].cells.length;
if(columCount != fieldArray.length){
//列与field不一致
return "";
}
var tdName = "";
var jsonArray = new Array();
for (var i = 1; i < rows; i++) {
//可能出现列合并,此种场景可以根据需要修改,在这里直接丢弃
var thisRowColumnCount = document.getElementById(tableid).rows[i].cells.length;
if(thisRowColumnCount != columCount){
continue;
}
var jsonItem = new Object();
for (var j = 0; j < columCount; j++) {
var tdName = fieldArray[j];
var tdValue = document.getElementById(tableid).rows[i].cells[j].innerHTML;
tdValue = tdValue.trim();
jsonItem[tdName] = tdValue;
}
jsonArray.push(jsonItem);
}
return JSON.stringify(jsonArray);
}
//call and output
var json = TableToJson("mytable");
console.log(json);
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8