对HTML表进行排序,通过JQuery进行追加

时间:2015-05-20 13:53:21

标签: javascript jquery tablesorter

您好我正在尝试使用Tablesorter(https://github.com/christianbach/tablesorter)对我的表进行排序,我通过JQuery.appends生成该表。这就是我的代码的样子:

$(document).ready(function() {


*Lotsa more code .....*



    $.get("../skillqueue",{keyid: keyid, charid: charid},function(xmlskillqueue){
    console.log("XML Skillqueue");
    console.log(xmlskillqueue);

    //Variables for
    var rowsets = xmlskillqueue.getElementsByTagName("rowset");
    var skillrows;

    for(var i = 0; i < rowsets.length; i++){
        if(rowsets[i].getAttribute("name") == "skillqueue"){
            skillrows = rowsets[i].getElementsByTagName("row");
        }
    }

    //Defines Table Headers
    $("#tableskillqueuelist").append(
            "<thead>" + 
            "<tr>" + 
            "<th>Order: </th> "+
            "<th>Skill Name: </th> "+
            "<th>Training to: </th> "+
            "<th>Starts:</th> "+
            "<th>Ends:</th> "+
            "</tr> "+
            "</thead>"+
            "<tbody>"
    );

    for(var i = 0; i < skillrows.length; i++){
        (function(i, skillrows) {

            $.get("../getitemname", {itemid:skillrows.getAttribute("typeID")},function(itemname){               
                $("#tableskillqueuelist").append(
                        "<tr> " + 
                        "<td>" + skillrows.getAttribute("queuePosition") + ". " +                           
                        "<td>" + itemname + "</td>" +
                        "<td>" +  "|Train to: " + skillrows.getAttribute("level") + "</td>" +
                        "<td>" +  "|Training Starts: " + skillrows.getAttribute("startTime") + "</td>" +
                        "<td>" +  "|Training Ends: " + skillrows.getAttribute("endTime") + "<td>" +                     
                        "</tr>"
                );
            })
        })(i, skillrows[i]);                    
    }
    //Ends the table body
    $("#tableskillqueuelist").append("</tbody>");
});
});

现在我想知道我需要做些什么来让它成功运行$(“#tableskillqueuelist”)。tablesorter();方法。因为看起来每当我尝试运行它时,#tableskillqueuelist似乎都是空的。

1 个答案:

答案 0 :(得分:2)

您需要告诉表格分类器您已经更改了数据,并且您希望通过触发事件对其进行排序。

文档示例:http://tablesorter.com/docs/example-ajax.html

$("table").tablesorter(); 
  $("#ajax-append").click(function() { 
     $.get("assets/ajax-content.html", function(html) { 
         // append the "ajax'd" data to the table body 
         $("table tbody").append(html); 
        // let the plugin know that we made a update 
        $("table").trigger("update"); 
        // set sorting column and direction, this will sort on the first and third column 
        var sorting = [[2,1],[0,0]]; 
        // sort on the first column 
        $("table").trigger("sorton",[sorting]); 
    }); 
    return false; 
});

HTH