gpt4 book ai didi

jquery - Html 表转 json 数组

转载 作者:行者123 更新时间:2023-12-01 06:22:38 25 4
gpt4 key购买 nike

我有一个带有动态行和列的表,我试图通过循环遍历每个 trtd 并在文本框中查找值,将 HTML 表转换为 Json,但没有运气好。这是我的 js 代码。

 $("#btn_Table2Json").click(function () {
var rows = [];
$('table.dynatable tbody tr').each(function (i, n) {
var $row = $(n);
if (n.className.toUpperCase() != "Prototype".toUpperCase() && n.className.toUpperCase() != "Header".toUpperCase()) {
$('table.dynatable tbody td').each(function (j, d) {
rows.push({
//Here id,Name,Address,Contact are dynamic.so need to find it inside of 'th' of table.
//but i am not being able to find it, so i just hard coded it :(
Id: $row.find('td:eq(0)').text(),
Name: $row.find('td:eq(1)').text(),
Address: $row.find('td:eq(2)').text(),
Contact: $row.find('td:eq(2)').text()
});
});
}
});
//debugger;
alert(JSON.stringify(rows));
//alert(table.toString());
});

TableJson

对于上表 JSON 输出应该是:

[{ID:"1",Name:"Bibek",Address:"lubhoo",Contact:"98411"},{ID:"4",Name:"Suraj",Address:"Sanagaun",Contact:"984511"}]

我的 Html 是(列和行是动态的)

<table class="dynatable">
<thead>
<tr class="Header">
<th id="AddRowTh"><button class="add">Add Row</button></th>
<th>ID &nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
<th>Name&nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
<th>Address&nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
<th>Contact&nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
<th id="AddColumnTh"><button style="width: 100px; height: 25px" class="addColumn">Add Column</button></th>
</tr>
</thead>
<tbody>
<tr class="prototype">
<td><p class="RowName"></p><a href="#" class="RemoveRow">Remove</a><!--<button class="remove">Remove</button>--></td>
<td><input type="text" name="id[]" value="0" class="id" /></td>
<td><input type="text" name="name[]" value="" /></td>
<td><input type="text" name="col4[]" value="" /></td>
<td><input type="text" name="col3[]" value="" /></td>
</tr>
</table>

最佳答案

试试这个

$('table.dynatable tr').each(function(){
rows.push({
Id: $(this).find('td:eq(1) input').val(),
Name: $(this).find('td:eq(2) input').val(),
Address: $(this).find('td:eq(3) input').val(),
Contact: $(this).find('td:eq(4) input').val()
});
});

DEMO

关于jquery - Html 表转 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17988732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com