【问题标题】:Iterating table columns & constructing JSON - jQuery迭代表列和构造 JSON - jQuery
【发布时间】:2015-09-27 14:37:14
【问题描述】:

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

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

格式是这样的

<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 需要是这样的: [{label:data, isPresent:data, value:data}, {..}, {..}]

我无法一次性获取两列 () 的数据,然后循环遍历接下来的 2 列。

【问题讨论】:

    标签: javascript jquery dom


    【解决方案1】:

    从你的问题来看,我假设你是 jQuery 的新手,所以我会给你一个简单的解决方案,可以在很多方面使用。

    我建议您在 HTML 中添加类。这样,我们就可以识别表格行的所有属性,而与 HTML 元素在 tr-tag 中的位置或数据放置在什么类型的标记中无关:

    <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 网站

    【讨论】:

    • 我能够做到,但这似乎是非常优雅的解决方案。我有一个问题。 for each 循环遍历行的每个 ,所以当我们执行find(".item-label") 时, 中没有该类的元素,那么它如何找到该元素的值?
    • 我忘了说列可以连续重复...解决方案中需要修改什么?
    • 我不确定我是否完全理解您在 cmets 中所说的内容。你能举一个更好的例子来说明你的 HTML 代码在不同类型的行和列中的样子吗?
    • 我已经编辑了这个问题。基本上在每一行中可以有超过 1 列具有相同的输入参数(单选按钮和复选框)。当我使用上述方法时,它仅适用于第一列
    • 尝试给带有单选按钮的 一个类(例如 item-option)。假设 td 的顺序始终相同,那么您可以使用 $(this).find(".item-label").each() 遍历不同的标签
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签