代码之家  ›  专栏  ›  技术社区  ›  MarkKGreenway

jquery每个json对象

  •  19
  • MarkKGreenway  · 技术社区  · 17 年前

    我有一个从一个服务返回的结果集,该服务为我提供了以下JSON

    {
        "ThreadCount":61,
        "GroupList":[
            {"userName":"KLT","count":2687},
            {"userName":"KCameron","count":718},
            {"userName":"IRG","count":156},{"userName":"JLB","count":123},{"userName":"HML","count":121},{"userName":"SMN","count":99},{"userName":"TBridges","count":68},{"userName":"ARF","count":65},{"userName":"MarkGreenway","count":61},{"userName":"SMC","count":55},{"userName":"EMD","count":52},{"userName":"PKP","count":41},{"userName":"KBounds","count":36},{"userName":"MAN","count":33},{"userName":"LAC","count":17},{"userName":"EPS","count":17},{"userName":"CAN","count":7},{"userName":"MAJ","count":3},{"userName":"CPC","count":2}]
    }
    

    我想使用jquery(或javascript)将线程计数放在一个DIV中,并将用户名和counds添加到表中。

    success: function(result) {
        $("#Unfiled").html(result.ThreadCount);
        $.each(result.GroupList, function(user) {
            $('#myTable > tbody').append(
                '<tr><td>'
                + user.userName
                + '</td><td>'
                + user.count +
                '</td></tr>'
            );
        });
    }
    

    因为某种原因,我没有得到任何东西在我的桌子上…

    顺便说一下,我的HTML在这里:

     <table>
        <tr>
            <td>
                Unfiled Emails:
            </td>
            <td id="Unfiled">
                -1
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <table id="myTable" border="2" cellpadding="3" cellspacing="3">
                </table>
            </td>
        </tr>
    </table>
    

    我知道我错过了一些简单的事情…

    谢谢你的帮助

    3 回复  |  直到 17 年前
        1
  •  42
  •   nickf    17 年前

    在提供给 each , this 引用当前元素。试试这个:

    $.each(result.GroupList, function() {
        $('#myTable > tbody').append(
            '<tr><td>'
            + this.userName
            + '</td><td>'
            + this.count +
            '</td></tr>'
        );
    });
    

    如果这对你不起作用,可能与此有关: $('#myTable > tbody') ,考虑到没有 tbody 元素。我相信Internet Explorer会自动创建一个浏览器,但其他浏览器不会。请检查 $.support.tbody 看看浏览器是否为你做了这些。

        2
  •  3
  •   Corey Ballou    17 年前

    我注意到你的桌子实际上没有tBody元素。这可能是你问题的一部分。

    $('#myTable > tbody').append.....
    
    <table id="myTable" border="2" cellpadding="3" cellspacing="3">
    </table>
    

    我还建议您在$.each()循环中创建一个字符串,然后在每个循环之后执行以下操作:

    $('#myTable > tbody').html(string);
    

    这将减少每次迭代数组时追加的开销。

        3
  •  2
  •   Kaleb Brasee    17 年前

    当我使用$.each()时,我使用了一个函数(i,item),其中i是一个表示索引的整数,item是实际对象。就是这样 the documentation 显示它正在完成——该方法被描述为函数回调(indexinarray,valueofelement)。