基于this tutorial我制作了JSON菜单。现在按ID排序的项目,但我需要按字母顺序对它们进行排序,并且不能理解如何做到这一点。我不确定array.sort();
是否有用
这是JS代码:
var builddata = function () {
var source = [];
var items = [];
for (i = 0; i < data.length; i++) {
var item = data[i];
var label = item["text"];
var parentid = item["parentid"];
var id = item["id"];
if (items[parentid]) {
var item = { parentid: parentid, label: label, item: item };
if (!items[parentid].items) {
items[parentid].items = [];
}
items[parentid].items[items[parentid].items.length] = item;
items[id] = item;
}
else {
items[id] = { parentid: parentid, label: label, item: item };
source[id] = items[id];
}
}
return source;
}
var source = builddata();
var buildUL = function (parent, items) {
$.each(items, function () {
if (this.label) {
var li = $("<li>" + this.label + "</li>");
li.appendTo(parent);
if (this.items && this.items.length > 0) {
var ul = $("<ul></ul>");
ul.appendTo(li);
buildUL(ul, this.items);
}
}
});
}
var ul = $("<ul></ul>");
ul.appendTo("#jqxMenu");
buildUL(ul, source);
HTML:
<div id='jqxMenu'>
</div>
这是JSFIDDLE