How to convert HTML table to Javascript Object with jQuery
这个问题的延伸。 我的表格是动态的,它的单元格具有 Html 内容,例如用于输入描述的输入和用于下拉选择的选择。
因此,为了将该 html 内容获取到 json 对象,创建了这个已回答的问题。
最佳答案
只需更改代码即可:
//
// for each table row in table body
//
var tbl = $('#students tbody tr').map(function (idxRow, ele) {
//
// start building the retVal object
//
var retVal = {id: ++idxRow};
//
// for each cell
//
var $td = $(ele).find('td').map(function (idxCell, ele) {
var input = $(ele).find(':input');
//
// if cell contains an input or select....
//
if (input.length == 1) {
var attr = $('#students thead tr th').eq(idxCell).text();
retVal[attr] = input.val();
} else {
var attr = $('#students thead tr th').eq(idxCell).text();
retVal[attr] = $(ele).text();
}
});
return retVal;
}).get();
console.log(tbl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="students" border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr class="student">
<td>Oscar</td>
<td><select>
<option value="21">21</option>
<option value="23" selected>23</option>
<option value="32">32</option>
</select></td>
<td><input type="text" value="16.5"></td>
</tr>
<tr class="student">
<td>Antonio</td>
<td><select>
<option value="21">19</option>
<option value="23">23</option>
<option value="32" selected>32</option>
</select></td>
<td><input type="text" value="14"></td>
</tr>
<tr class="student">
<td>Jessica</td>
<td><select>
<option value="21" selected>21</option>
<option value="23">23</option>
<option value="32">32</option>
</select></td>
<td><input type="text" value="19"></td>
</tr>
</tbody>
</table>
关于javascript - 当列有输入字段时,将 Html Table 转换为 Json,l输入文本或选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44313731/