通过数组的遍历,动态生成树形节点,对后端数据的要求降低,只需要一个数组即可。

 

树形菜单

  1. <!DOCTYPE html> 
  2. <html> 
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
  5. <title>树形节点</title> 
  6. <style type="text/css"> 
  7. .ui-treenode ul li{ 
  8.     list-style:url("images/tree/tree2.JPG"); 
  9.     padding: 4px; 
  10.     background: url('images/tree/tree4.JPG') no-repeat 0px 5px; 
  11.     font-size: 12px; 
  12.     text-indent: 20px; 
  13. .ui-treenode ul li.cur{ 
  14.     background: url('images/tree/tree3.JPG') no-repeat 0px 5px; 
  15.     list-style:url("images/tree/tree1.JPG"); 
  16. </style> 
  17. <script type="text/javascript" src='http://code.jquery.com/jquery-latest.min.js'></script> 
  18. <script type="text/javascript"> 
  19. (function($){ 
  20.     var self = null
  21.     $.fn.TreeNode = function(cfg,callback){ 
  22.         self = $(this); 
  23.         //默认0为根节点 
  24.         self.attr('nodeId',0); 
  25.          
  26.         var default_cfg = { 
  27.                 data:null 
  28.         };  
  29.          
  30.         var _config = $.extend({},default_cfg,cfg); 
  31.          
  32.         var data = _config.data; 
  33.          
  34.         var fn = { 
  35.                 createNode: function(parent){ 
  36.                     var son = parent.next(); 
  37.                     var nodeId = parent.attr('nodeId'); 
  38.                      
  39. //                  如果是第一次打开  则创建   否则使用已有的节点 
  40.                     if(nodeId == 0 || son[0]&&son[0].nodeName != 'UL'){ 
  41.                         var dom = ""
  42.                         //判断是否为叶子节点 
  43.                         if(parent && $(parent).attr('nodeId') != undefined && data.length > 0){ 
  44.                             dom = "<ul>"
  45.                             if(data && typeof data == "object") 
  46.                             $.each(data,function(i){ 
  47.                                 var obj = data[i]; 
  48.                                 if($(parent).attr('nodeId') == obj.parentId){ 
  49.                                     dom += "<li nodeId="+obj.id+">"+obj.text+"<input type='checkbox'/></li>"; 
  50.                                 } 
  51.                             }); 
  52.                             dom += "</ul>"; 
  53.                             $(parent).attr('nodeId') == 0 ? $(dom).appendTo(parent) : $(dom).insertAfter(parent).hide().slideDown(200,function(){ 
  54.                                 var isChecked = $(this).prev('li').find('input:checkbox').attr('checked'); 
  55.                                 $('li',this).each(function(){ 
  56.                                     $('