For this question我創建了以下示例解決方案:http://jsfiddle.net/PKcnb/3/。只有最後的AJAX請求在加載的表中排序
該代碼通過YouTube API請求50個視頻(由於請求限制)。每個請求將追加一個新的行到最終表。我想要一個簡單的排序解決方案,所以我使用jquery.sortElements.js。
sortElement.js似乎可以工作,但它只是對上一次請求的視頻進行排序。爲什麼整個表沒有排序?搜索周圍,它看起來像我需要implement .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 = $("<tr></tr>");
newRow.append("<td>" + title + "</td>");
newRow.append("<td class='dur'>" + duration + "</td>");
$("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('<span title="sort this column"/>').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;
});
});
最大的問題是,它做的時間列文本排序,而不是數字排序。 –
現場是爲事件處理程序...不適合您的分揀機。只需要在添加新數據後調用排序 – charlietfl
@ Beetroot-Beetroot,就是這個問題。在我添加parseInt()後,表中的所有項目都能正確排序。謝謝你指出我正確的方向。 – JSuar