动态表行未在DOM中以正确的顺序显示

时间:2012-12-17 16:35:15

标签: javascript jquery ajax html-table

 success: function (data, status) {
            var header = $("#MainDiv");

            header.html(null);
            var headertemplate = $("<table class='searchlistbody'><tr></th><th>Name</th></tr>");
            header.append(headertemplate);

            $.each(data, function () {
                var template = $("<tr> <td class='campnameAltrow'><span class='searchListTitle'></span></td></tr>");

                        template.find('span.searchListTitle').attr('title', this.Title);

                // add the template to the collection
                header.append(template);
            });
            header.append("</table>");
        },

现在,当我试图在桌面上设置边框时,我发现它只是在标签上应用边框,即标题(名称)。

 Debugging further in fire bug I saw that the DOM sequence is in this format
        <table class='searchlistbody'><tr><th>Name</th></tr></table>
        <tr> <td class='campnameAltrow'>Test</td></tr>
        <tr> <td class='campnameAltrow'>Test</td></tr>
        <tr> <td class='campnameAltrow'>Test</td></tr>
        <tr> <td class='campnameAltrow'>Test</td></tr>
        <tr> <td class='campnameAltrow'>Test</td></tr>

任何人都可以告诉我为什么在附加所有for循环行之前表关闭....它是一个AJAX调用

2 个答案:

答案 0 :(得分:1)

从append函数的文档判断:http://api.jquery.com/append/它实际上尝试使用正确的DOM元素

请勿尝试将其用作字符串连接操作

而是尝试创建表元素并在其中单独附加TH和TR:

var table = $("<table ...></table>")
table.append("<th>...</th>")
$.each(function() {
  ...
  table.append("<tr>...</tr>")
  ...
})

答案 1 :(得分:0)

您无法添加拼接到dom的元素。因此,您向表头添加一个表,然后将行追加到表

 success: function (data, status) {
            var header = $("#MainDiv");

            header.html(null);
            var headertemplate = $("<table class='searchlistbody'><tr></th><th>Name</th></tr></table>");
            header.append(headertemplate);

            $.each(data, function () {
                var template = $("<tr> <td class='campnameAltrow'><span class='searchListTitle'></span></td></tr>");

                        template.find('span.searchListTitle').attr('title', this.Title);

                // add the template to the collection
                headertemplate.append(template);
            });
        },