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

时间:2017-11-22 13:58:09

标签: javascript jquery html ajax

过去我使用Vanilla JS循环Ajax返回数据并构建表。对于这个项目,我想使用JQuery。原因是,我的一些td元素需要具有特殊属性。在我看来,使用JQuery添加这些属性会更容易。以下是我的例子:

    $.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);               
    });

由于某些原因,上面的代码没有产生任何表格行。我想知道是什么打破了我的代码。如果有人可以提供帮助,请告诉我。我的每个表行都应该分配了使用Ajax调用数据返回的唯一ID。我不确定追加是否会导致一些问题。如果有人看到问题,请告诉我。

1 个答案:

答案 0 :(得分:1)

您的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);               
    });

当你追加它们时关闭。

此外,表元素未创建,因此尚不存在