我有一个 javascript,应该显示像这样的图像的项目:
但它并没有像图像那样按字母顺序生成它们。
这是一个示例(仅包括 HTML 和 CSS,它基本上显示了执行 javascript 后如何呈现):
看看:http://jsbin.com/UHiZUJU/20/edit
生成这些带有大字母的项目的 JavaScript 如下:
$(".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]);
}
});
所以我的问题是如何按字母顺序对它们进行排序?
这是一个测试 JSbin,其中包含 CSS、HTML 和 javascript,但 javascript 在按钮单击时执行,仅用于测试。
最佳答案
在使用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(...
关于javascript - 当我的目录列表使用 javascript 显示项目时,如何确保它按字母顺序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19266216/