javascript - jQuery: Group <a> links based on text value -
jquery noob here - needing help.
basically, because go's html/template output sucks, i'm forced use more js (which suck at!)
i have ordered, not grouped list of links, need grouping "parent folder" links, text value. file/folder tree.
the list dynamic, based follows:
<div id="files"> <a>file.rb</a> <a>somefile.rb</a> <a>folder</a> <a>folder/level2</a> <a>folder/level2/file.js</a> <a>folder/level2/level3/anotherfile.js</a> </div>
so files need grouped parent folder, , folders grouped recursively text in 'a' element. parent 'a' 'folder' , child 'files' within folder.
unfortunately, folder , file 'a's can't given separate classes on generation due underlying go script. output expanded directory of folders / files in ordered, not grouped links.
re: comment below: example desired output following:
http://labs.abeautifulsite.net/archived/jquery-filetree/demo/
i understand mean splitting files/folders ul/li lists, i'm fine that. it's detection of file vs folder & folder level link text struggling with.
any appreciated! thanks! :)
is you're looking for?
$(document).ready(function(){ var alist = $('#files > a'); var filelist = []; $.each($('#files > a'), function(i, obj){ filelist.push($(obj).html()); }); var tree = getnodetree(filelist); console.log(tree); var html = drawmenu(tree, "http://www.google.nl"); console.log(html); $('#files').html(html); }); function getnodetree(filelist){ if(filelist.length === 0){ return []; } var childtree = []; $.each(filelist, function(i, path){ var nodenames = path.split("/"); if(childtree[nodenames[0]]===undefined){ childtree[nodenames[0]] = []; childtree[nodenames[0]]['files'] = []; } if(nodenames.length>1){ var childpath = nodenames.slice(1).join("/"); childtree[nodenames[0]]['files'].push(childpath); } }); for(var key in childtree) { childtree[key]['name'] = key; childtree[key]['files'] = getnodetree(childtree[key]['files']); } return childtree; } function drawmenu(tree, basepath){ var elements = ""; for(var key in tree) { var node = tree[key]; var path = basepath + "/" + node['name']; var childmenu = drawmenu(node['files'], path); elements += $('<div><li><a href="'+ path + '">' + node['name'] + childmenu + '</a></li></div>').html(); } if(elements.length>0){ elements = '<ul>'+elements+'</ul>'; } return $('<div>'+elements+'</div>').html(); }
Comments
Post a Comment