只有加载表中的最后一个AJAX请求排序

对于这个问题,我创建了以下示例解决方案: http : //jsfiddle.net/PKcnb/3/ 。

该代码通过YouTube API请求50个video(由于请求限制)。 每个请求都会在最终表中附加一个新行。 我想要一个简单的排序解决方案,所以我使用了jquery.sortElements.js。

sortElement.js似乎可以工作,但它只是对上次发出的请求中的video进行排序。 为什么整个表没有排序? 搜索一下,看起来我需要实现.live(),但我的尝试都没有成功。

相关的JQuery

// Recursive function to grab the next set of videos function getVideos(index, max) { $.ajax({ url: 'https://gdata.youtube.com/feeds/api/playlists/UUAuUUnT6oDeKwE6v1NGQxug?v=2&orderby=duration&max-results=50&start-index=' + index, // 'https://gdata.youtube.com/feeds/api/users/tedtalksdirector/uploads', dataType: "xml", success: function(xml) { var videos = $(xml).find("entry"); videos.each(function() { var title = $(this).find("title").text(); var duration = $(this).find("duration").attr("seconds"); var minutes = Math.floor(duration / 60); var seconds = (duration % 60); if (seconds < 10) seconds = "0" + seconds; var newRow = $(""); newRow.append("" + title + ""); newRow.append("" + duration + ""); $("tbody#videos").append(newRow); }); newIndex = index + 50; $('#VideosLoaded').html(newIndex - 1); if (newIndex < max) { getVideos(newIndex, max); } } }); } // Make table sortable (jquery.sortElements.js) // via https://stackoverflow.com/questions/5066002/sending-one-ajax-request-at-a-time-from-a-loop var table = $('table'); $('#Title, #Duration').wrapInner('').each(function() { var th = $(this), thIndex = th.index(), inverse = false; th.click(function() { table.find('td').filter(function() { return $(this).index() === thIndex; }).sortElements(function(a, b) { return $.text([a]) > $.text([b]) ? inverse ? -1 : 1 : inverse ? 1 : -1; }, function() { // parentNode is the element we want to move return this.parentNode; }); inverse = !inverse; }); });​ 

我认为排序例程会更好地工作:

 $('#Title, #Duration').wrapInner('').each(function() { var th = $(this), thIndex = th.index(), inverse = false; th.click(function() { table.find('td').filter(function() { return $(this).index() === thIndex; }).sortElements(function(a, b) { var id = th.attr('id'), a = (id === 'Duration') ? parseInt($(a).text()) : $(a).text(), b = (id === 'Duration') ? parseInt($(b).text()) : $(b).text(), x = (a === b) ? 0 : (a > b) ? 1 : -1; return (x === 0) ? 0 : inverse ? -x : x; }, function() { return this.parentNode; }); inverse = !inverse; }); }); 

更新小提琴