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;
}
function htmlTableToJson(table, edit = 0, del = 0) {
// If exists the cols: "edit" and "del" to remove from JSON just pass values = 1 to edit and del params
var minus = edit + del;
var data = [];
var colsLength = $(table.find('thead tr')[0]).find('th').length - minus;
var rowsLength = $(table.find('tbody tr')).length;
// first row needs to be headers
var headers = [];
for (var i=0; i<colsLength; i++) {
headers[i] = $(table.find('thead tr')[0]).find('th').eq(i).text();
}
// go through cells
for (var i=0; i<rowsLength; i++) {
var tableRow = $(table.find('tbody tr')[i]);
var rowData = {};
for (var j=0; j<colsLength; j++) {
rowData[ headers[j] ] = tableRow.find('td').eq(j).text();
}
data.push(rowData);
}
return data;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="answered">
<tbody>
<tr>
<td data-id="user.email">email@email.com</td>
<td data-id="meme.yodawg">Yo Dog! I Heard you liked answers, so I answered your question, with a method wrapped in a jQuery plugin!</td>
</tr>
</tbody>
</table>
8条答案
按热度按时间px9o7tmv1#
取自John Dyer's Blog
wvmv3b1j2#
我对上面的所有解决方案都不满意,最后编写了自己的jQuery插件来实现这一点,它与解决方案非常相似,但接受几个选项来定制结果,如忽略隐藏行、覆盖列名和覆盖单元格值
插件可以在这里找到一些例子沿着如果这是更多的你在寻找什么:https://github.com/lightswitch05/table-to-json
zbwhf8kr3#
请尝试
$("#"+tableID + " tr")
。4jb9z9bj4#
您应该会发现以下内容很有帮助:http://encosia.com/use-jquery-to-extract-data-from-html-lists-and-tables/
ugmeyewa5#
这一条对我很有效:(我的表中只有两行,th和td)
67up9zun6#
带有标题和正文的HTML表格:
xkrw2x1b7#
ruoxqz4g8#
下面是成功解析合并行的示例。
--合并行示例:
--解析