简体   繁体   中英

How can I make sure that my directory listing sorts in alphabetical order when it displays the items with javascript?

I have a javascript that should displays items like this image:

But it is not generating them in a alphabetical order like the image.

Here is a example how it is(only HTML & CSS included, its shows basicly how its rendered after the javascript has been executed):

Take a look at: http://jsbin.com/UHiZUJU/20/edit

The javascript that generates these items with its Big letter is following:

 $(".processlinks-section-item-title2 a").each(function() {
                   var text = $(this).text();
                   var href = $(this).attr('href');
                   if (!text.length) return;
                   var letter = text.substr(0, 1).toUpperCase();
                   if (letter.match(/[0-9]/g)) 
                       letter = "#";

                   var list = $('.processlinks-section-template');
                   var section = list.children('[data-letter="'+letter+'"]');
                   if (!section.length) {
                       var section = $('<div class="processlinks-section-item" data-letter="' + letter + '"></div>');
                       if (!list.children().length) {
                           list.append(section);
                       } else {
                           // find right element so list is sorted
                           section.insertAfter(list.children()[0]);
                       }
                   }
                   var item = $('<div class="processlinks-section-item-title">' + '<a href="' + href + '">' + text + '</a>');
                   if (!section.children().length) {
                       section.append(item);
                   } else {
                       // find right element so list is sorted
                       item.insertAfter(section.children()[0]);
                   }

               });

So my question is how can I sort these in alphabetical order?

Here is a testing JSbin where CSS,HTML and javascript is included but the javascript executes on button click, its just for testing.

Take a look at: http://jsbin.com/aMElAba/5/edit

Sort the items before using each :

$(".processlinks-section-item-title2 a").sort(function(a, b) {
    var letterA = $(a).text().charAt(0).toUpperCase(),
        letterB = $(b).text().charAt(0).toUpperCase();
    return letterA > letterB ? -1 : (letterA < letterB ? 1 : 0);
}).each(...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM