2017-10-19 98 views
-1

我現在有一個問題,我用下面的代碼的子菜單:在菜單js中按字母順序排列?

load_sub_menu_disciplines: function() { 
    $.ajax({ 
headers: { 
    "Accept": "application/json; charset=utf-8", 
    "Content-Type": "application/json; charset=utf-8" 
}, 
type: 'GET', 
url: 'api/catalog_system/pub/specification/fieldvalue/22', 
success: function(data) { 
    $.each(data, function(i, ele) { 
     if (ele.IsActive) { 
      $('#disciplinas .box-link .nav').append($('<li/>').append($('<a/>').attr('href', '/' + ele.Value + '?map=specificationFilter_22&O=OrderByReleaseDateDESC').text(ele.Value))) 
     } 
    }); 
    $('#disciplinas a:empty').remove(); 
}, 
error: function(error) { 
    console.log(error); 
} 

});

我需要你按字母順序排序,但我不知道該怎麼做。我明白我應該使用排序功能來完成,但我不知道如何統一代碼。 Im noob in js -.-

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort –

回答

-1

處理這個問題最簡單的方法是在將數據附加到DOM之前對數據進行排序。

success: function(data) { 
    data.sort(function(a, b) { 
     if (a.Value == b.Value) { return 0; } 
     if (a.Value > b.Value) { return 1; } 
     return -1; 
    }); 

    $.each(data, function(i, ele) { 
     if (ele.IsActive) { 
      $('#disciplinas .box-link .nav') 
       .append($('<li/>') 
       .append($('<a/>') 
       .attr('href', '/' + ele.Value + '?map=specificationFilter_22&O=OrderByReleaseDateDESC') 
       .text(ele.Value))) 
     } 
    }); 
    $('#disciplinas a:empty').remove(); 
},