javascript - 做一个无限节点的树结构插件的原理
迷茫
迷茫 2017-04-11 11:27:24
[JavaScript讨论组]
因为公司功能扩展需要,所以我想做一个无限树结构的插件来进行更新。
但是目前遇见了这样的一个问题,假如数据如下:
    {
        name: '水果', id: 1, children: [
            {name:'水果1',id:2,children:[
                {name:'水果2',id:3,children:[
                    {name:'水果2',id:3,children:[]}        
                ]}
            ]}
        ]
    }

像这种无限扩展的子级,我每一层的每一个数据我都需要添加一个status对象。每一个层级都需要添加一个内层循环。但是我感觉这种办法太死了。请问有什么便捷的技巧或者写法呢?
于是我想到了能否用for来for,但是尝试了一下发现不行。
我又想到能否用递归实现呢?但是小弟对递归的作用还不算太明白所以没有实现。
想问下,像我这种问题有什么办法可以实现用最少的代码做到每个数据里面都能给他一个status呢?

app.directive('tree',function(){
    return {
        restrict:'E',
        replace:true,
        scope:{
            list:"=",
            resData:"=",
            layer:"@"
        },
        templateUrl:"template/tree.html",
        link:function(scope,elem,attr){
            console.log(scope.list)
            for(var i in scope.list){
                scope.list[i].status=false;
                if(scope.list.children){
                    for(var k in scope.lists[i].children){
                        scope.list[i].children[k].status=false;
                    }
                }
            }
        }
    }
})
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
ringa_lee
  var data = [{name: '水果', id: 1, children: [
            {name:'水果1',id:2,children:[
                {name:'水果2',id:3,children:[
                    {name:'水果2',id:3,children:[]}        
                ]}
            ]}
        ]
    }];
    
 function render(data){
         
    data.forEach(function(item,index){
        item.status = false;
        if(item.children){
            render(item.children);
        }
    }); 
    console.log(JSON.stringify(data));
    return data;
 }
 
 render(data);
迷茫
function set(obj){ 
  if(!!!obj.status) obj.status = "1"; 
  if(obj.children.length > 0)
     $.each(obj.children, function(i,o){set(o)});
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号