简体   繁体   English

循环对象数据在JQuery中创建tr和td元素?

[英]Loop over Object data create tr and td elements in JQuery?

In the past I used Vanilla JS to loop over Ajax return data and build the table. 过去,我使用Vanilla JS遍历Ajax返回数据并构建表。 For this project I would like to use JQuery. 对于这个项目,我想使用JQuery。 Reason why, some of my td elements need to have special attributes. 为什么我的某些td元素需要具有特殊属性。 In my opinion adding these attributes would be easier with JQuery. 我认为使用JQuery添加这些属性会更容易。 Here is example of what I have: 这是我所拥有的示例:

    $.ajax({
        type: 'POST',
        url: 'Application.cfc?method=findRec',
        data: {'recNum':recNum},
        dataType: 'json'
    }).done(function(obj){ 
        var tbl = "<table id='myTbl'><thead><tr><th>Last</th><th>First</th></thead><tbody>";

        $.each(obj.DATA, function(i, item) {  
 $('#myTbl').append($('<tr>').attr('id',$.trim(decodeURIComponent(item.REC_ID))).append(
              $('<td>').text($.trim(decodeURIComponent(item.LASTNAME))),
              $('<td>').text($.trim(decodeURIComponent(item.FIRSTNAME)))                    
            )
        });
        tbl += "</tbody></table>";
    }).fail(function(jqXHR, textStatus, errorThrown){
        alert("Error: "+errorThrown);               
    });

For some reason code above didn't produce any table rows. 由于某种原因,上面的代码没有产生任何表行。 I'm wondering what is breaking down my code. 我想知道是什么破坏了我的代码。 If anyone can help please let me know. 如果有人可以帮忙,请告诉我。 Each of my table rows should have assigned unique ID that is returned with Ajax call data. 我的每个表行都应该分配一个唯一的ID,该ID随Ajax调用数据一起返回。 I'm not sure if append is causing some problems. 我不确定append是否会引起一些问题。 If anyone see the problem please let me know. 如果有人看到问题,请告诉我。

There is no closing tags for your tr and td tags: tr和td标签没有结束标签:

    var tbl = "<table id='myTbl'><thead><tr><th>Last</th><th>First</th></tr></thead><tbody>";

        $.each(obj.DATA, function(i, item) {  
 $('#myTbl').append($('<tr>').attr('id',$.trim(decodeURIComponent(item.REC_ID))).append(
              $('<td>').text($.trim(decodeURIComponent(item.LASTNAME))),
              $('<td>').text($.trim(decodeURIComponent(item.FIRSTNAME)))                    
            )
        });
        tbl += "</tbody></table>";
    }).fail(function(jqXHR, textStatus, errorThrown){
        alert("Error: "+errorThrown);               
    });

Close then when you append them as well. 当您附加它们时也请关闭。

Furthermore, the table element is not created and therefore does not exist yet . 此外,表元素尚未创建,因此尚不存在

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM