我想在我的网站上存储一个表格数据。该表有n行,每行都有m列(它是一个动态表)。每个单元格都有一个输入。所以我们有n * m输入。
如何以JSON格式存储数据?
Example:
|------------------|------------------|------------------|
| {row-1,column-1} | {row-1,column-2} | {row-1,column-3} |
|------------------|------------------|------------------|
| {row-2,column-1} | {row-2,column-2} | {row-2,column-3} |
|------------------|------------------|------------------|
| {row-3,column-1} | {row-3,column-2} | {row-3,column-3} |
|------------------|------------------|------------------|
| {row-4,column-1} | {row-4,column-2} | {row-4,column-3} |
|------------------|------------------|------------------|存储的数据:
JSON Object:
[
[ {"row-1,column-1"},{"row-1,column-2"},{"row-1,column-3"} ], // row 1
[ {"row-2,column-1"},{"row-2,column-2"},{"row-2,column-3"} ], // row 2
[ {"row-3,column-1"},{"row-3,column-2"},{"row-3,column-3"} ], // row 3
[ {"row-4,column-1"},{"row-4,column-2"},{"row-4,column-3"} ] // row 4
]是否有任何jQuery解决方案或plugin?
发布于 2016-06-11 03:21:51
首先使用each获取每个tr,并在其中使用另一个each()获取row的事件td。然后将每个td的文本添加到object中。在结尾处将对象转换为json。
var obj = [];
$("table tr").each(function(index){
obj[index] = [];
$(this).find("td").each(function(index2){
obj[index][index2] = [$(this).text()];
});
});
var json = JSON.stringify(obj);
console.log(json);table, tr, td {
border: 1px solid black;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Row1-Column1</td>
<td>Row1-Column2</td>
<td>Row1-Column3</td>
</tr>
<tr>
<td>Row2-Column1</td>
<td>Row2-Column2</td>
<td>Row2-Column3</td>
</tr>
<tr>
<td>Row3-Column1</td>
<td>Row3-Column2</td>
<td>Row3-Column3</td>
</tr>
</table>
https://stackoverflow.com/questions/37754799
复制相似问题