这里为大家展示一下前段时间自定义了一个树型下拉框,相对功能比较简单,欢迎引用或改造。让我们先来看一下效果:

自定义树型下拉框
     接下来,我们做个简单的拆解和说明:
1、javacript 脚本
 1 $(function () {
 2     $('.treedropdown').each(function () {
 3         var id = $(this).attr('id') + "_tree";
 4         var loca = $(this).offset();
 5         $(this).after('<span class="tree" >);
 6 
 7         $('#' + id)
 8             .offset({ top: loca.top, left: loca.left })
 9             .hover(function () {
10                 $(this).show();
11             }, function () {
12                 $(this).fadeOut();
13             });
14 
15         $(this).click(function () {
16             $.target = $(this);
17             $('#' + $(this).attr('id') + '_tree').fadeIn('100');
18         });
19     });
20     GetDataSource('');
21 });
脚本初始化

      在初始化中我们为页面中 class 标记了 “treedropdown” 的元素创建一个 “tree” 的容器,及指定数据将在这里绑定树型结构,并指定位置。笔者将定义文本框的单击事件来触发显示 “Tree”。

 1 function GetDataSource(id) {
 2     isAll = false;
 3     $.post('datasource.json', function (json) {
 4         var tree = eval(json);
 5         if ($('.tree').html() == "") {
 6             for (var i in tree) {
 7                 var node = tree[i];
 8                 $('.tree').append('<dl class="treenode"><dt class="nodename rooticon" tree>);
 9                 addChildren(node.children, true);
10             }
11         } else {
12             if (json == "[]") {
13                 var icon = $('dt[tree>;
14                 $('dt[tree>, icon);
15             } else {
16                 addChildren(tree);
17                 var dt = $('dt[tree>);
18                 if (dt.nextAll('dt').length > 0) {
19                     dt.next().addClass('joinicon');
20                 }
21             }
22         }
23         if (isAll) {
24             CheckNodeStatus();
25         }
26     });
27 }
绑定数据源

      在这里我们请求 JSON 数据源,使用 jQuery 的 append 方法追加到 “tree”中。代码中 “isAll” 是一个布尔类型的变量,初始值为 “false”,它表示该数据源提供不完整数据,及展开节点将判断读取其子节点。这里需要读者根据使用需求自行改造。

 1 function addChildren(children, isroot) {
 2     for (var i in children) {
 3         var node = children[i];
 4         var pId = node.parentid;
 5         var foldicon = (parseInt(i) + 1) == children.length ? 'foldlasticon' : 'foldicon';
 6         var unfoldicon = (parseInt(i) + 1) == children.length ? 'unfoldlasticon' : 'unfoldicon';
 7         if (i == 0) {
 8             $('dt[tree>);
 9         } else {
10             $('dt[tree>);
11         }
12 
13         if (node.children != null && node.children.length > 0) {
14             addChildren(node.children);
15             isAll = true;
16         }
17     }
18 }
添加子节点

相关文章:

  • 2021-05-28
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-08
  • 2022-12-23
  • 2021-12-18
  • 2018-04-16
  • 2021-05-31
相关资源
相似解决方案