jQuery:如何获取具有自定义标头值的表数据的 JSON 数据。有一张表,需要将整个表数据转换为json格式数据。现在我尝试替换 json 数据中插入实际表头的标头数组(自定义标头)。我尝试用下面的代码替换原始的表头$headers =["ID", "ABC", "XYZ","Test"];
,
预期输出:
[{"ID":"22222","ABC":"test5","XYZ":"3000","":"abc"},{"ID":"3333","ABC":"test1","XYZ":"1000","":"erf"},{"ID":"44444","ABC":"test2","XYZ":"2000","":"sde"},{"ID":"55555","ABC":"test3","XYZ":"3000","":"fre"}]
$(document).ready(function() {
$("#getJsondata").click(function() {
var jsonData1 = [];
var matchId = 1234;
var $headers = $("#firstTable").find("th:eq(0),th:eq(1),th:eq(2)");
//var $headers =["ID", "ABC", "XYZ","Test"];
var $rows = $("#firstTable").find("tbody tr")
.each(function(index) {
const $cells = $(this).closest("tr").find("td:eq(0),td:eq(1),td:eq(2),td:eq(3)");
jsonData1[index] = {};
$cells.each(function(cellIndex) {
jsonData1[index][$($headers[cellIndex]).text()] = $(this).text();
});
});
alert(JSON.stringify(jsonData1));
});
});
td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="multipleData" style="border:1px solid black;" id="firstTable">
<thead style="background:grey;">
<tr>
<th>Header1</th>
<th>Header2</th>
<th>Header3</th>
<th>Header4</th>
<th>Header5</th>
<th>Header6</th>
</tr>
</thead>
<tbody>
<tr style="border:1px solid black">
<td>22222</td>
<td>test5</td>
<td>3000</td>
<td>abc</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>3333</td>
<td>test1</td>
<td>1000</td>
<td>erf</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>44444</td>
<td>test2</td>
<td>2000</td>
<td>sde</td>
<td>22222</td>
<td>Y</td>
</tr>
阿波罗的战车
阿晨1998
相关分类