javascript - 迭代表列并构建 JSON - jQuery

标签 javascript jquery dom

这可能是一个微不足道的问题,但我有点困惑如何提取列数据和构造对象。

该表本质上是动态的,根据提供的数据生成。

格式是这样的

<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/

相关文章:

javascript - 哪些 javascript/php 模板库将解析相同的模板文件?

javascript - JQuery .find() 可以通过 id 查找,但不能通过类查找

python - XML 解析 - ElementTree vs SAX 和 DOM

javascript - 如何根据屏幕的像素宽度制作 JavaScript 函数 "off limits"?

javascript - 如何在函数中引用自身而不考虑外部变量的变化?

javascript - 如何使用 angular-filter 库实现二级分组?

javascript - 创建菜单子(monad)菜单,单击更改并显示 + - 符号展开与否

javascript - jquery:即使在处理数字时我也必须使用 parseInt(),为什么?

javascript - 有必要在div容器上使用masonry吗?

php - 如何在 PHP 中使用 Dom 文档查找 Dom 元素的样式属性?