JsTree:如何使用顶部

时间:2016-12-09 13:25:25

标签: jquery sorting jstree directory alphabetical

我使用插件Jstree绘制文件夹和文件树。

我想获取文件列表顶部的文件夹列表(文件夹和文件列表必须按字母顺序排序)。

我有启动树的功能:

$('#jstree_demo_div').jstree({ 
    'core' : {
        'data' : [

            {"id":"index_0","text":"test_folder","parent":"#","icon":""},
            {"id":"index_1","text":"vide","parent":"index_0","icon":""},
            {"id":"index_2","text":"05nesf-sdfdgd.mp4","parent":"index_1","icon":"fa fa-film"},
            {"id":"index_3","text":"naissance-d-une-fleur-ouwzp9me-41.mp4","parent":"index_0","icon":"fa fa-film"},
            {"id":"index_4","text":"za05nesfsdfsdg.mp4","parent":"index_0","icon":"fa fa-film"},
            {"id":"index_5","text":"ddd","parent":"#","icon":""},
            {"id":"index_6","text":"05nes-ibw6q9me-41.mp4","parent":"index_5","icon":"fa fa-film"},
            {"id":"index_7","text":"tom-jerry-soundscape-ttar8gme-41.mp4","parent":"#","icon":"fa fa-film"},
            {"id":"index_8","text":"aaes-qmc8q-9me-41.mp4","parent":"#","icon":"fa fa-film"},
            {"id":"index_9","text":"bb05nes.mp4","parent":"#","icon":"fa fa-film"}
        ]
    },
    'plugins' : ['sort','types'],
    'sort' : function(a, b) {
        //What is the function of sorting
    },
});

我初始化的结果: Tree

我需要使用哪种排序功能?

2 个答案:

答案 0 :(得分:11)

您可以按图标排序,然后按文字排序:

'sort' : function(a, b) {
        a1 = this.get_node(a);
        b1 = this.get_node(b);
        if (a1.icon == b1.icon){
            return (a1.text > b1.text) ? 1 : -1;
        } else {
            return (a1.icon > b1.icon) ? 1 : -1;
        }

这是jsfiddle

答案 1 :(得分:0)

Alexandre 的扩展答案 - 如果您希望文件夹位于顶部(默认图标)和其余节点按字母顺序排列:

 sort: (a, b) => {
   a1 = $('#jstree_demo_div').jstree(true).get_node(a); // default change the selector
   b1 = $('#jstree_demo_div').jstree(true).get_node(b);
                
   if (a1.icon === true || b1.icon === true) { // if either of the nodes is a folder (no icon)
     if (a1.icon === true && b1.icon !== true) { // a is folder, b is leaf, we push folder up
        return 1;
     }
                     
     if (a1.icon !== true && b1.icon === true) { // a is leaf, b is folder, we push folder up
       return 1;
     }
                     
     return (a1.text > b1.text) ? 1 : -1; // a is folder, b is folder -> alphabetically
   }
   else {
     return (a1.text > b1.text) ? 1 : -1; // a is leaf, b is leaf -> alphabetically
   }
 }

jstree 在没有提供图标时使用 true 作为图标的默认值。通过这种排序设置,您的叶子可以有不同的图标,并且仍会正确排序(按字母顺序排列文件夹,然后按字母顺序排列叶子)。