Link to home
Create AccountLog in
Avatar of Techsavy
Techsavy

asked on

help understand JQuery $.each

Hi,

I have following code  that builds a folder tree based on url paths stored in an array called folderArray. However I am having trouble understanding this code on how the recursion is happening. Can anyone explain me this with detailed notes please?



 
    //build the tree here after getting all the folders into array

        var rootDiv = $("<div></div>").appendTo("#folderTree");
        var elements = {};

        //iterate through array
        $.each(folderArray, function () {

            var parent = elements[this.substring(0, this.lastIndexOf("/"))]

            //if there exists a parent then create a new list.
            var list = parent ? parent.next() : rootDiv;

            if (!list.length) {

                list = $("<div style='margin-left:50px;'></div>").insertAfter(parent);


            }

            var item = $("<div style='margin-left:50px;'></div>").appendTo(list);

            var anchor =  $("<a target='_blank'></a>").attr("href", this).text(this.substring(this.lastIndexOf("/") + 1)).appendTo(item);
           
            var folderIcon = $("<img border='0' src='_layouts/Images/folder.gif'/>").prependTo(anchor);
           
           
            elements[this] = item;


        });
ASKER CERTIFIED SOLUTION
Avatar of Jagadishwor Dulal
Jagadishwor Dulal
Flag of Nepal image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer