jsTree:如何从jstree获取所有叶节点?

时间:2012-04-24 07:50:22

标签: javascript jquery jquery-plugins jquery-selectors jstree

我想从jsTree获取所有叶节点(节点的ID和文本)?

我没有使用复选框ui:jsTree。

   Root
      -----A
           -----A1
                  -----A1.1

           -----A2
                  -----A2.1

      -----B

           -----B2

       -----C
            -----C1
                  -----C1.1

我想要来自jsTree的叶子节点列表。

预期产出:[A1.1,A2.1,B2,C1.1]

对此事项的任何帮助或指导将不胜感激。

2 个答案:

答案 0 :(得分:5)

这样的东西?

$('.jstree-leaf').each(function(){
  var id   = $(this).attr('id');
  var text = $(this).children('a').text();
});

答案 1 :(得分:-1)

////////////////////////////////////////////////////////////////////
// @name        :
// @description :   function
// @params      :
// @return      :
////////////////////////////////////////////////////////////////////
function jstreeIterateNodes(
    treeOwner ,
    node , 
    fnCallbackCondition ,
    bRecursive ,
    arrCollector
){

    var 
        childNodes = node.children ,
        arrCollector = ( arrCollector ) ? arrCollector : [] ,
        bUseCallback = ( typeof fnCallbackCondition === "function" ) ? true : false ,
        nodeItreator = null;

    for(
        var i = 0;
        i < childNodes.length;
        ++i
    ){

        nodeItreator = treeOwner.get_node( childNodes[i] );

        if( bUseCallback ){

            if( fnCallbackCondition( nodeItreator , node ) ){

                arrCollector.push({
                    node : nodeItreator,
                    parent : node
                });

            }

        }
        if( bRecursive ){
            jstreeIterateNodes(
                treeOwner ,
                nodeItreator ,
                fnCallbackCondition ,
                arrCollector
            ); 
        }
    }

    return arrCollector;
}
var 
    _your_jstree_ = $("#YOUR_TREE_ELEMENT").jstree( true ) ,
    bRecursiveItreation = false , // could be true for recursive
    arrCollected = null;

arrCollected = jstreeIterateNodes( 
    _your_jstree_ , 
    _your_jstree_.get_node( "some_node_id" ) , 
    function _your_filter_callback_( itrated_node , parent_itrated_node ){
      // Do what ever and return true to collect
    } ,
    bRecursiveItreation 
);

// DO SOMTHING WITH arrCollected which contains all collected nodes