javascript - Determine which level i'm in the JSON tree -


i may have simple problem, can't figure out. if have multy denominational json array so:

[     {         "name":"one",         "children":         [             {                 "name":"two",                 "children":                 [                     {                         "name":"two",                         "children": []                     },                      ...                  ]              },             ...         ]      } ] 

i want determine level i'm at. if going loop true first entities printed bellow:

one -|      2 -> view children 

once "view children" clicked:

one -|      2 -|            3 -> view children || go back. 

and if "go back" clicked go to:

one -|      2 -> view children 

so it's similar hierarchy. can't figure out how make button work. able figure out go forward using peace of code:

level = obj; // obj json data.  function inside(events){     temp = "";     (i in events) {       temp += "<li id='"+events[i].id+"' class='"+events[i].type+"' index='"+i+"''>&nbsp;&nbsp;"+events[i].name+ "</li>";     }     return temp; }  text += inside(obj);  $('#filebrowser').on('click','li.folder',function(e){      var index =  $(this).attr('index');     var html = "<li class='folder back' index='"+index+"'>back</li>";      if(level[index].children){         html = html + inside(level.[index].children);         level = level[index].children;     }       $('#filebrowser').html(html);     e.stoppropagation();  }); 

i wanted can dynamic, many go back's should occur, storing obj in variable not going cut it.

generally stacks used keep track of things navigation history. programming languages include implementations of sort of stack structure. in javascript stack functionality built array structure. check out push() , pop() methods.

as navigate forward can push() last page onto history stack. button pressed can pop() entries off in same order added, until reach first entry.

it might this:

var backstack = []; $('#filebrowser').on('click','li.folder',function(e){      var index =  $(this).attr('index');     var html = "<li class='folder back' index='"+index+"'>back</li>";      if(level[index].children){         html = html + inside(level.[index].children);         level = level[index].children;     }       backstack.push($('#filebrowser').html);     $('#filebrowser').html(html);     e.stoppropagation();  }); 

then on button pressed:

$('#filebrowser').html(backstack.pop()); 

or along lines.


Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -