如何将HtmlTable单元格转换为json对象? [英] How to Convert an HtmlTable cells to json object?
本文介绍了如何将HtmlTable单元格转换为json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从表格的每一行中的所有单元格构造一个html表格中的json对象。即,如果我的html表格由10行组成,每行10行,我需要创建一个包含所有10行的json对象,以及10列。如何用json对象实现这一点?
是否可以通过单击将这个大对象保存到数据库?
帮助请。
解决方案
使用此方法:
函数tableToJson(table){
var data = []; //第一行需要是标题var headers = [];
for(var i = 0; i< table.rows [0] .cells.length; i ++){
headers [i] = table.rows [0] .cells [i] .innerHTML .toLowerCase()。replace(/ / gi,'');
}
//通过单元格
(var i = 1; i< table.rows.length; i ++){
var tableRow = table.rows [i] ; var rowData = {}; (var j = 0; j rowData [headers [j]] = tableRow.cells [j] .innerHTML;
;
} data.push(rowData);
}
返回数据;
}
礼貌: http://johndyer.name/html-table-to-json/
I need to frame a json object from an html table with all the cells in each rows of the table. i.e,
if my html table consists of 10 rows, 10 columns each for a row, i need to create a json object with all the 10 rows and the data within the 10 columns. How can this be possible with a json object?
Is it possible to save this big object to the db on a single click?
Help Please. Thank You.
解决方案
Use this method:
function tableToJson(table) {
var data = []; // first row needs to be headers var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i]; var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
} data.push(rowData);
}
return data;
}
Courtesy: http://johndyer.name/html-table-to-json/
这篇关于如何将HtmlTable单元格转换为json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文