javascript - Generating a nodes path from an unordered list -
i have following list of data:
which set html:
<ul id='tree'> <li data-id="1" data-parent="0"> home <ul> <li data-id="2" data-parent="1"> <ul> <li data-id="4" data-parent="2"> </li> </ul> </li> <li data-id="3" data-parent="1"> contact <ul> <li data-id="5" data-parent="3"> employees <ul> <li data-id="6" data-parent="5"> full-time </li> <li data-id="7" data-parent="5"> part-time </li> </ul> </li> </ul> </li> </ul> </li> </ul>
upon clicking button, want generate node path each list item , add string of data can format.
i have started this:
$('button').on('click', function(){ var output = ""; $("ul#tree li").each(function(){ var id = $(this).data("id"); var parent = $(this).data("parent"); output = output + "id=" + id + "&parent=" + parent + "$"; }); $("section").html(output); });
which generates:
id=1&parent=0 id=2&parent=1 id=4&parent=2 id=3&parent=1 id=5&parent=3 id=6&parent=5 id=7&parent=5
however, want add node path of each line (the path of parent id's current list item). so, example, this:
id=1&parent=0&node_path=.0. id=2&parent=1&node_path=.0.1. id=4&parent=2&node_path=.0.1.2. id=3&parent=1&node_path=.0.1. id=5&parent=3&node_path=.0.1.3. id=6&parent=5&node_path=.0.1.3.5. id=7&parent=5&node_path=.0.1.3.5.
i'm not sure how create function combine parent id's in path of ul > li's...
you use parents(), list of parents. take further , rid of parent data attribute together, simplify following code.
$('#mybutton').on('click', function () { var output = ""; $("ul#tree li").each(function () { var id = $(this).data("id"); var parent = $(this).data("parent"); output = output + "id=" + id + "&parent=" + parent + "&node_path="; var node_path = parent + "."; $(this).parents('li').each(function() { node_path += $(this).data("parent") + "."; }); output += node_path.split('').reverse().join('') output += "<br/>"; }); $("#mysection").html(output); });
Comments
Post a Comment