循环遍历表返回未定义的结果

时间:2015-11-19 11:34:18

标签: javascript jquery

我必须记下用户可以删除的活动。这些活动都在一张桌子上,我试图迭代,但我觉得我差不多了。我使用Bootstrap 3和jQuery。我还是jQuery的新手。

这是我用来创建模态窗口的HTML,所以我可以将控件放在那里:

<div id="delete-activity-modal" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1>Delete Activity</h1>
            </div>
            <div class="modal-body">
                <div class="input-group">
                    <span class="input-group-addon" id="add-addon-styling">Choose Activity</span>
                    <select class="form-control" id="delete-activity-modal-dropdown">
                        <!-- Options Added via content-controller.js -->
                    </select>
                    <span class="input-group-addon" data-toggle="tooltip" data-placement="top"
                          title="Choose the activity from the drop-down menu you want to delete.">
                        <b>?</b>
                    </span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger btn-bg" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Result

如上所述,这就是我的结果。我应该有6个结果,他们应该有一个活动ID和一个名字,但他们回来时未定义,所以我可能做错了:P

以下是我用来制作下拉内容的功能:

function CreateActivityDeleteDropdown() {
    var dropdown = $('#delete-activity-modal-dropdown');
    $('#activityTable').each(function() {
        var activityId = $(this).attr("#activityId");
        var activityName = $(this).attr("#activityName");
        var dropdownDescription = activityId + " | " + activityName;
        var dropdownElement = '<option value="' + activityId + '">' + dropdownDescription + '</option>';
        $(dropdown).append(dropdownElement);
    });
}

只有在按下按钮时才会调用此功能,因此执行此操作时表格确实存在。当网站加载时,我需要动态添加我需要查看的表:

function GetActivityAbstracts() {
    $.getJSON(, function (testData) {
        var object = $.parseJSON(testData);
        var activityTable = '<tbody id="activityTable"></tbody>';
        $.each(object, function () {
            var activityId = this['ActivityId'];
            var activityName = this['ActivityName'];
            var activityResponsible = this['Responsible'];
            var activityEstimatedSavings = parseFloat(this['EstimatedSavings']).toFixed(2);
            var activityEstimatedStart = this['EstimatedStart'];
            var activityEstimatedEnd = this['EstimatedEnd'];
            var activityStatus = this['Status'];
            // TODO: Make more user-friendly Status Descriptions instead of C# enum values.
            var tableElement =
                    '<tr>' +
                    '<td id = "activityId" style = "vertical-align: middle; align: center;">'
                    + activityId + '</td>' +
                    '<td style = "vertical-align: middle;">' +
                    '<div class="status-circle" data-toggle="tooltip" data-placement="right"' +
                    'title=" ' + activityStatus + '" style="background-color:' +
                    GetColumnColor(activityStatus) + ';"></div></td>' +
                    '<td id = "activityName" style = "vertical-align: middle;">'
                    + activityName + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityResponsible + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedSavings + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedStart + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedEnd + '</td>' +
                    '</tr>';
            activityTable += tableElement;
        });
        $('#current-data-table').append(activityTable);

        /* This call is necessary because the table is added dynamically */
        $('[data-toggle="tooltip"').tooltip();
    });
}

结果:

enter image description here

一些JSON示例数据:

"{\"1\":{\"ActivityId\":1,\"ActivityName\":\"Noget Med Penge\",\"Responsible\":\"Name\",\"EstimatedSavings\":9001.0,\"EstimatedStart\":\"19-11-2015\",\"EstimatedEnd\":\"01-01-2016\",\"Status\":\"NA\"},\"2\":{\"ActivityId\":2,\"ActivityName\":\"We need to shut down the bluetooth RAM hard drive!\",\"Responsible\":\"Name\",\"EstimatedSavings\":24589.0,\"EstimatedStart\":\"23-05-2014\",\"EstimatedEnd\":\"10-12-2015\",\"Status\":\"ON_TRACK\"},\"3\":{\"ActivityId\":3,\"ActivityName\":\"We need to encode the wireless RAM interface!\",\"Responsible\":\"Name\",\"EstimatedSavings\":874561.0,\"EstimatedStart\":\"11-04-1970\",\"EstimatedEnd\":\"22-01-2016\",\"Status\":\"DONE\"},\"4\":{\"ActivityId\":4,\"ActivityName\":\"We need to reboot the open-source PNG program!\",\"Responsible\":\"Name\",\"EstimatedSavings\":812654.0,\"EstimatedStart\":\"18-08-2000\",\"EstimatedEnd\":\"19-04-2016\",\"Status\":\"ISSUE\"},\"5\":{\"ActivityId\":5,\"ActivityName\":\"We need to program 
the mobile CPU bus!\",\"Responsible\":\"Name\",\"EstimatedSavings\":-47998.0,\"EstimatedStart\":\"29-07-1982\",\"EstimatedEnd\":\"22-05-2016\",\"Status\":\"BEHIND\"},\"6\":{\"ActivityId\":6,\"ActivityName\":\"We need to network the optical GB port!\",\"Responsible\":\"Name\",\"EstimatedSavings\":74511.0,\"EstimatedStart\":\"23-10-1992\",\"EstimatedEnd\":\"27-09-2016\",\"Status\":\"ABANDONED\"}}"

2 个答案:

答案 0 :(得分:1)

首先,正如我所说,GetActivityAbstracts会创建重复的id。在上面的代码<td id = "activityId"<td id = "activityName"内的$.each将会重复。也可以使用 .find 代替 .attr 来查找每个tr内的元素,以便将id更改为类或者从index添加.each以生成唯一的id

function GetActivityAbstracts() {
    $.getJSON(, function (testData) {
        var object = $.parseJSON(testData);
        var activityTable = '<tbody id="activityTable"></tbody>';
        $.each(object, function (index,value) {
            //index here is used to generate unique ids
            var activityId = this['ActivityId'];
            var activityName = this['ActivityName'];
            var activityResponsible = this['Responsible'];
            var activityEstimatedSavings = parseFloat(this['EstimatedSavings']).toFixed(2);
            var activityEstimatedStart = this['EstimatedStart'];
            var activityEstimatedEnd = this['EstimatedEnd'];
            var activityStatus = this['Status'];
            // TODO: Make more user-friendly Status Descriptions instead of C# enum values.
            var tableElement =
                    '<tr>' +
                    '<td id = "activityId_'+index+'" style = "vertical-align: middle; align: center;">'
                    + activityId + '</td>' +
                    '<td style = "vertical-align: middle;">' +
                    '<div class="status-circle" data-toggle="tooltip" data-placement="right"' +
                    'title=" ' + activityStatus + '" style="background-color:' +
                    GetColumnColor(activityStatus) + ';"></div></td>' +
                    '<td id = "activityName_'+index+'" style = "vertical-align: middle;">'
                    + activityName + '</td>' +
                    //Add index for ids here
                    '<td style = "vertical-align: middle;">'
                    + activityResponsible + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedSavings + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedStart + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedEnd + '</td>' +
                    '</tr>';
            activityTable += tableElement;
        });
        $('#current-data-table').append(activityTable);

        /* This call is necessary because the table is added dynamically */
        $('[data-toggle="tooltip"').tooltip();
    });
}

现在,一旦您生成了唯一元素,您就可以循环浏览每个tr,如下所示:

function CreateActivityDeleteDropdown() {
    var dropdown = $('#delete-activity-modal-dropdown');
    $('tbody#activityTable tr').each(function() {
        var activityId = $(this).find("td [id^='activityId']").text();
        //get value from the td whose id starts with activityId
        var activityName = $(this).find("td [id^='activityName']").text();
        //get value from the td whose id start with activityName
        var dropdownDescription = activityId + " | " + activityName;
        var dropdownElement = '<option value="' + activityId + '">' + dropdownDescription + '</option>';
        $(dropdown).append(dropdownElement);
    });
}

现在,如果您将td id更改为class,如下所示:

function GetActivityAbstracts() {
    $.getJSON(, function (testData) {
        var object = $.parseJSON(testData);
        var activityTable = '<tbody id="activityTable"></tbody>';
        $.each(object, function () {
            var activityId = this['ActivityId'];
            var activityName = this['ActivityName'];
            var activityResponsible = this['Responsible'];
            var activityEstimatedSavings = parseFloat(this['EstimatedSavings']).toFixed(2);
            var activityEstimatedStart = this['EstimatedStart'];
            var activityEstimatedEnd = this['EstimatedEnd'];
            var activityStatus = this['Status'];
            // TODO: Make more user-friendly Status Descriptions instead of C# enum values.
            var tableElement =
                    '<tr>' +
                    '<td class = "activityId" style = "vertical-align: middle; align: center;">'
                    + activityId + '</td>' +
                    '<td style = "vertical-align: middle;">' +
                    '<div class="status-circle" data-toggle="tooltip" data-placement="right"' +
                    'title=" ' + activityStatus + '" style="background-color:' +
                    GetColumnColor(activityStatus) + ';"></div></td>' +
                    '<td class= "activityName" style = "vertical-align: middle;">'
                    + activityName + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityResponsible + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedSavings + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedStart + '</td>' +
                    '<td style = "vertical-align: middle;">'
                    + activityEstimatedEnd + '</td>' +
                    '</tr>';
            activityTable += tableElement;
        });
        $('#current-data-table').append(activityTable);

        /* This call is necessary because the table is added dynamically */
        $('[data-toggle="tooltip"').tooltip();
    });
}

您可以再次使用 .find 获取tdclass相应的内容,如下所示:

function CreateActivityDeleteDropdown() {
    var dropdown = $('#delete-activity-modal-dropdown');
    $('#activityTable tr td').each(function() {
        var activityId = $(this).find(".activityId").text();
        var activityName = $(this).find(".activityName").text();
        //getting using class
        var dropdownDescription = activityId + " | " + activityName;
        var dropdownElement = '<option value="' + activityId + '">' + dropdownDescription + '</option>';
        $(dropdown).append(dropdownElement);
    });
}

<强>更新

创建 DEMO

时发现了一些问题

您正在使用var activityTable = '<tbody id="activityTable"></tbody>';,最后,一旦您创建了一行,您就会使用activityTable += tableElement;。由于&#39; activityTable variable already had activityTable + = used to append as ...&#39; which is why a new tbody was getting created when appended to DOM . So either make it tbody通过执行以下操作来对象:

var activityTable = $('<tbody id="activityTable"></tbody>');

然后您可以使用.append append创建tr内的tbody,如下所示:

$(activityTable).append(tableElement); 

而不是activityTable += tableElement;

如果您愿意按照自己的方式行事,那么只要添加了</tbody>所有内容,就可以添加rows,如下所示:

var activityTable = '<tbody id="activityTable">'; //从此处删除

$.each完成后你可以做到

activityTable+="</table>";

答案 1 :(得分:0)

编辑(示例):

HTML:

<table>
    <thead>
        <th>
            Activity ID
        </th>
        <th>
            Status
        </th>
        <th>
            Activity name
        </th>
    </thead>
    <tbody id="activityTable">
    </tbody>
</table>

<select>
</select>

JS:

$(document).ready(function(){
    var JSONData = [[1,1,"name1"], [2,1,"name2"]];
    var html = "";
    var count = 0;
    $.each(JSONData, function(){
        html += "<tr>";
        html += "<td data-type='id'>" + JSONData[count][0] + "</td>";
        html += "<td data-type='status'>" + JSONData[count][1] + "</td>";
        html += "<td data-type='name'>" + JSONData[count][2] + "</td>";
        html += "</tr>";
        count++;
    });
    var createOption;
    $("#activityTable").html(html);
    $("select").html("");
    $("#activityTable tr").each(function(){
        var data_id = $(this).find("td[data-type=id]").html();
        var data_name = $(this).find("td[data-type=name]").html();
        createOption = "<option>" + data_id + " | " + data_name;
        $("select").append(createOption);
    });
});

输出:

enter image description here

演示:Click