2012-05-26 17 views
0

http://jsbin.com/aboca3/95/edit數字列表,然後按字母順序使用jQuery?

下面是單獨的數字和字母排序的工作示例。

它運作良好,問題是,它不按字母順序排列與<em>數字相等的項目。

E.g.它給數字排序Salpinestars(58),喬·火箭(58)。應該給相反的順序。

我試圖將items.sort(sortEm).prependTo(self);更改爲items.sort(sortAlpha).sort(sortEm).prependTo(self);,但它不起作用。

有什麼想法?

+0

它顯示了您的示例中的Joe Rocket(58)和Salpinestars(58)(FF和Chrome)。如何重現問題? –

+0

打開http://jsbin.com/aboca3/95/edit#javascript,html,live,點擊「... 19更多選擇」,然後點擊「...更少的選擇」。 – Jasper

+0

「.sort(sortAlpha).sort(sortEm)」背後的想法是首先按字母排序,然後按中的數字排序。 – Jasper

回答

3

使用此sortEm():

function sortEm(a,b){ 
    var emA = parseInt($('em',a).text().replace(/[\(\)]/g,'')); 
    var emB = parseInt($('em',b).text().replace(/[\(\)]/g,'')); 
    if (emA == emB) { // sort alphabetically if em number are equal 
    return sortAlpha(a,b); 
    } 
    return emA < emB ? 1 : -1; 
} 
+0

謝謝丹尼斯!不錯的方法 – Jasper

2

您可以編寫一個函數由兩個標準來排序。

// ORDER BY EmValue, LiMinusEmText 

function sortBoth(a, b) { 
    var aText = $(a).text().replace(/\(\d+\)\s*$/, "");  // chop off the bracket 
    var bText = $(b).text().replace(/\(\d+\)\s*$/, "");  // and numbers portion 
    var aValue = +$(a).find("em").text().replace(/\D/g, ""); // parse out em value 
    var bValue = +$(b).find("em").text().replace(/\D/g, ""); // and convert to number 
    if (aValue == bValue) { 
     if (aText == bText) { 
      return 0; 
     } 
     else if (aText < bText) { 
      return -1; 
     } 
     else /*if (aText > bText)*/ { 
      return 1; 
     } 
    } 
    else { 
     return aValue - bValue; 
    } 
} 

// ORDER BY LiMinusEmText, EmValue 

function sortBoth(a, b) { 
    var aText = $(a).text().replace(/\(\d+\)\s*$/, "");  // chop off the bracket 
    var bText = $(b).text().replace(/\(\d+\)\s*$/, "");  // and numbers portion 
    var aValue = +$(a).find("em").text().replace(/\D/g, ""); // parse out em value 
    var bValue = +$(b).find("em").text().replace(/\D/g, ""); // and convert to number 
    if (aText == bText) {         // strings value same? 
     return aValue - bValue;        // then return a - b 
    } 
    else if (aText < bText) { 
     return -1; 
    } 
    else /*if (aText > bText)*/ { 
     return 1; 
    } 
} 
+0

+ $(a).find(「em」)。text()。replace(/ \ D/g,「」); // Brilliant :) –

+0

是這樣做的。 – matchdav

+0

只要史蒂夫仍然需要sortAlpha()按照他如何使用演示的說明。所以他更好地重用sortAlpha()而不是它的代碼。 –

相關問題