这可能是一个微不足道的问题,但我有点困惑如何提取列数据和构造对象。
该表本质上是动态的,根据提供的数据生成。
格式是这样的
<tr>
<td> Label </td>
<td>
<input type = "radio" value="yes"/> YES
<input type = "radio" value="no"/> NO
<textarea>
</td>
<td>
<input type = "radio" value="yes"/> YES
<input type = "radio" value="no"/> NO
<textarea>
</td>
// This structure can repeat
...
...
</tr>
// Rows will repeat themselves
到目前为止我已经记下了
$(function () {
$('#submit').click(function () {
var i = 0;
var t = document.getElementById('table');
$("#table tr").each(function () {
var columns = $(this).find('td');
/* how to extract column data here?, so that I construct
a column object and keep looping for the other columns
});
});
我的 JSON 需要是这样的: [{标签:数据,isPresent:数据,值:数据},{..},{..}]
我无法一次性获取两列 () 的数据,然后循环接下来的两列。
最佳答案
从你的问题来看,我假设你对 jQuery 很陌生,所以我将为你提供一个可以多种方式使用的简单解决方案。
我建议您向 HTML 添加类。这样,我们就可以识别表格行的所有属性,而与 HTML 元素在 tr 标签中的位置或数据放置在什么类型的标签中无关:
<tr>
<td class="item-label"> Label </td>
<td>
<input class="item-option-yes" type="radio" value="yes"/> YES
<input class="item-option-no" type="radio" value="no"/> NO
</td>
... other cells with data ...
</tr>
... other rows ...
在每个函数中,您可以组合 $(this) 和 find() 函数来构造 JSON 对象
$(function () {
$('#submit').click(function () {
var itemArray = [];
$("#table tr").each(function (index) {
var itemData = {
"label": $(this).find(".item-label").text(),
"isPresent": $(this).find(".item-option-yes")[0].checked,
"value": $(this).find(".some-other-class").text()
};
itemArray.push(itemData);
});
});
有关 find、$(this) 和each-functions 的更多信息,请查看 jQuery 网站
关于javascript - 迭代表列并构建 JSON - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809052/