0

我有一个 xml 文件:-

<child_4 entity_id="4" value="Activities" parent_id="2">
    <child_10066 entity_id="10066" value="Physical1" parent_id="4">
        <child_10067 entity_id="10067" value="Cricket" parent_id="10066">
            <child_10068 entity_id="10068" value="One Day" parent_id="10067"/>
        </child_10067>
    </child_10066>
    <child_10069 entity_id="10069" value="Test2" parent_id="4"/>
    <child_10070 entity_id="10070" value="Test3" parent_id="4"/>
    <child_10071 entity_id="10071" value="Test4" parent_id="4"/>
    <child_10072 entity_id="10072" value="Test5" parent_id="4"/>
    <child_5 entity_id="5" value="Physical" parent_id="4"/>
</child_4>

我想得到这样的结果:-

第一眼:-

Activities
Test2
Test3
Test4
Test5
Physical

单击Activities下拉子列表后:-

Activities
          Physicall
Test2
Test3
Test4
Test5
Physical

如果点击Physicall

Activities
          Physicall
                   Cricket
Test2
Test3
Test4
Test5
Physical

像树类型的东西
看起来像下拉菜单......
谢谢......

4

1 回答 1

1

我做了jquery版本

var xml = [
'<child_4 entity_id="4" value="Activities" parent_id="2">',
    '<child_10066 entity_id="10066" value="Physical1" parent_id="4">',
        '<child_10067 entity_id="10067" value="Cricket" parent_id="10066">',
            '<child_10068 entity_id="10068" value="One Day" parent_id="10067"/>',
        '</child_10067>',
    '</child_10066>',
    '<child_10069 entity_id="10069" value="Test2" parent_id="4"/>',
    '<child_10070 entity_id="10070" value="Test3" parent_id="4"/>',
    '<child_10071 entity_id="10071" value="Test4" parent_id="4"/>',
    '<child_10072 entity_id="10072" value="Test5" parent_id="4"/>',
    '<child_5 entity_id="5" value="Physical" parent_id="4"/>',
'</child_4>'
].join('');

和代码是:

function makeHtml( $xml , $ul ){

     $xml.each( function(){

            var $node =  $(this) ;

            var $li = $('<li></li>').html( $node.attr('value') );

            $ul.append( $li ); 

            if ( $node.children().length > 0 ) {

                 $childUl = $('<ul></ul>').hide(); 

                 $ul.append( $childUl ); 

                 // toggle hide and show
                 $li.click( function(){

                        if( $(this).next().css('display') == 'none') {
                            $(this).next().show();
                        } else {
                            $(this).next().hide();
                        }  
                 });

                 makeHtml( $node.children() , $childUl );
            }                        

    }); 
} 

makeHtml( $( xml ) , $('ul') );

并添加到 jsfiddle http://jsfiddle.net/PLH8D/3/

于 2013-03-30T09:39:53.080 回答