2013-08-23 3 views
0

Может ли кто-нибудь помочь мне создать следующий JSON в следующем HTML?Javascript Recursion JSON в HTML

Мне так плохо в рекурсии, что это даже не смешно. Я не могу найти что-либо на SO, чтобы помочь мне, как мне нужно, вы увидите мой jsFiddle как я!

Я пытаюсь превратить это:

var data = [ 
    { 
     "node_id":1, 
     "children":[] 
    }, 
    { 
     "node_id":2, 
     "children":[] 
    }, 
    { 
     "node_id":3, 
     "children":[ 
      { 
       "node_id":4, 
       "children":[] 
      }, 
      { 
       "node_id":5, 
       "children":[ 
        { 
         "node_id":6, 
         "children":[] 
        }, 
        { 
         "node_id":7, 
         "children":[] 
        } 
       ] 
      } 
     ] 
    } 
]; 

В это:

<ul> 
<li>1 
    <ul> 
     <li>2 
     <ul> 
      <li>3 
       <ul> 
        <li>4</li> 
        <li>5 
         <ul> 
          <li>6</li> 
          <li>7</li> 
         </ul> 
        </li> 
       </ul> 
      </li> 
     </ul> 
    </ul> 
</li> 
</ul> 

Это моя лучшая попытка (See My jsFiddle) после запуска через некоторые SO вопросы. Я так смущен рекурсией:

Обновление: Я приближаюсь, но это так сложно. Похоже, если бы я сделал document.createElement и добавленные дети, он мог бы работать лучше?

function recursion(data, is_child, first_call) { 

    if (is_child != true) { 
     var output = '<ul id="org">\n'; 
    } 
    else if (is_child == true && first_call == true) { 
     var output = '<ul>\n'; 
    } 
    var len = data.length; 
    for (var i = 0; i < len; i++) 
    { 
     if (is_child == true && first_call == true) { 
      output += '<li>'+ data[i].node_id +'</li>\n'; 
     } else { 
      output += '<li>'+ data[i].node_id +'\n'; 
     } 

     if (data[i].children.length > 0) { 
      if (is_child == true && first_call != true) { 
       first_call = true 
      } else { 
       first_call = false 
      } 
      output += recursion(data[i].children, true, first_call); 
     } 
     else { 
      if (is_child == true && first_call != true) { 
       output += '</li>'; 
      } 

      if (typeof data[i+1] != 'undefined') { 
       output += '<ul>\n'; 
      } else { 
       // Close all the items that are not closed 
       for (var j = 0; j < i; j++) { 
        output += '</li></ul>\n' 
       } 
       output += '</li>\n' 
      } 
     } 

    } 
    output += '</ul>\n'; 

    return output; 
} 

Update: Thee путь узел обрабатывается, если она имеет детей, кажется, есть другое поведение. У меня есть это изображение, чтобы показать вам, что он правильно отображает этот плагин. jOrgChart: enter image description here

+0

Вы уверены, что html, который вы вставили выше, является вашим выводом? Мне кажется, что у узлов 1 и 2 не должно быть детей –

+0

Не думаю. Я пытаюсь подключить это в этот плагин jQuery Flowchart «jOrgChart», пример @ http://dl.dropboxusercontent.com/u/4151695/html/jOrgChart/example/example.html - и вы можете увидеть источник, который они элементы гнезда действительно смешные. – JREAM

+0

Я согласен с @JustinBicknell, в вашем примере вывода вы обрабатываете узлы 2 и 3 по-другому, чем узлы 4 и 5. Обе пары являются братьями и сестрами в вашем JSON, но у вас есть первый родитель/ребенок в вашем примере HTML. – SlightlyCuban

ответ

0

Я смог понять это, я просто имел свой ум во многих местах. Вот ответ:

recursion = function(data, is_child) { 
    var output = ''; 
    if (typeof is_child == 'undefined') { 
     is_child = false; 
    } 

    // start:ul (only one of these) 
    if (is_child == false) { 
     output += '<ul id="org">\n'; 
    } 

    // end:ul 
    var len = data.length; 
    for (var i = 0; i < len; i++) 
    { 
      // If this is a child loop, and its the first iteration, it 
     // has a special case: 
     // <ul> 
     // <li>first</li> 
     // <li>second<ul> 
     var first_child_item = false; 
     if (is_child == true && i == 0) { 
      first_child_item = true; 
     } 

     // open:main wrapper 
     if (first_child_item == true) { 
      output += '<ul class="first_child_item">\n'; 
      output += '<li>' + data[i].node_id + '</li>\n'; 
      continue; 
     } else { 
      if (is_child) { 
       // When there is a child with another beside it 
       output += '<li>' + data[i].node_id; 
      } else { 
       // the main low level call 
       output += '<ul class="low_level">\n'; 
       output += '<li>' + data[i].node_id; 
      } 
     } 

     // open:children seek 
     if (data[i].children.length > 0) 
     { 
      output += recursion(data[i].children, true); 
     } 

     // close pending tags 
     if (typeof data[i+1] == 'undefined') 
     { 
      for (var j = 0; j < i; j++) { 
       output += '</li>\n'; 
       output += '</ul>\n'; 
      } 
     } 
    } 
    // end main:ul (only one of these) 
    output += '</ul>\n'; 

    return output; 
} 
Смежные вопросы