简体   繁体   中英

How to save HTML ul-li structure into javascript object

i have this following html structure usilg ul and li.

<ul class="treeview" id="productTree">
   <li class="collapsable lastCollapsable">
     <div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div>
     <span id="top1" class="">top1</span>
     <ul>
       <li class="collapsable lastCollapsable">
         <span class="">mod1</span>
         <ul>
           <li class="last">
              <span>bottom1</span>
           </li>
         </ul>
       </li>
     </ul>
   </li>
   <li class="collapsable lastCollapsable">
     <span id="top2" class="">top2</span>
     <ul>
       <li class="collapsable lastCollapsable">
         <span class="">mid2</span>
           <ul>
             <li class="last">
                <span>bottom2</span>
             </li>
           </ul>
        </li>
      </ul>
    </li>
</ul>

the website allows user to add more data under this structure and am using jquery treeview to show the tree structure dynamically. Now i need to save this whole ul-li structure into a js object for future use in the website. how do i achieve this? the last node("bottom1 and bottom2 here") has a class "last" if that helps. as we can add data dynamically we can be sure how much levels of ul li is there at the end when user clicks "save"

You can use recursive function to save a tree object;

function save(obj_ul, tree){

    var obj_lis = obj_ul.find("li")

    if (obj_lis.length == 0) return;        

    obj_lis.each(function(){
        var $this = $(this);
        if($this.parent("ul").get(0) == obj_ul.get(0))
        {
            tree.push({
                name : $this.find('> span').text(),
                child : save($this.find("ul").first(), [])
            });


        }
    });
    return tree;
}

console.log(save($('#productTree'), []));

If you want to reprouce the same thing verbatim, as a string of HTML elsewhere on the site, you could just do this? Then .append() or .prepend() treeview where you like.

​var treeview = $('#productTree').parent().html()

Assuming you want JSON:

function save(){
    var tmp = [];

    $('#productTree li.collapsable').each(function(){
        var $this = $(this),
            $spans = $this.find('span'),
            o = [];

            $spans.each(function(){
               o.push($(this).text())
            })

            tmp.push(o);
    });
    return tmp;
}

You could also use map() to accomplish the same thing, too.

EDIT: Updated, assuming your text will live inside a span . This will create an array of arrays, each containing the text from the span s inside each of your list-items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM