JsTree: 如何将带文件夹的节点置于顶部并对 jstree 进行排序

9

我使用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个回答

15

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

'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
明白了,通过更改为 a1.icon < b1.icon。再次感谢!^ - 夏期劇場
@Alexandre,这些排序函数会忽略子文件夹。你有没有解决方法可以对子文件夹进行排序? - Mar Tin

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作为图标的默认值。通过这种排序设置,您的叶子节点可以有不同的图标,并且仍然会被正确地排序(文件夹按字母顺序排列,然后按字母顺序排列叶子节点)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接