开发者

DOM structure to array

I'm working on "menu designer" - a tool to edit menu structure in the app's backend. I have html code like this

<ul id="menu-designer-control">
    <li id="mi-2">
        <h3>Submenu header</h3>     
        <ul>
            <li id="mi-4"><h4>Hello world - article</h4></li>

            <li><!-- Drop here --></li>
        </ul>
    </li>
    <li id="mi-1">
        <h3>Hello world - article</h3>      
        <ul>
            <li><!-- Drop here --></li>
        </ul>
    </li>

</ul>

And I want to get array like this in PHP.

array(    
    2 /* top level item id */ => array( 4 /* children id */ ), 
    1 => array() /* or null or whatever */    
);

Could you please give me an advice how to do it? I've tried .sortable( 'serialize );, I've tr开发者_如何学运维ied using each (on all li-s). Nothing with success - furthermore I'm not much familiar with javascript arrays :- / (So I'm pretty unsure how it should look and how to send it to the server… as a JSON object/string?).

Thank you a lot

(I'm using jQuery.)


function children(ul) {
  var lis = ul.children(), obj = {};
  lis.each(function(i, li) {
    var id = $(li).attr('id').substr(3);
    if ( id ) {
      obj[id] = children($('> ul', li));
    }
  });
  return obj;
}

var obj = children($('ul#menu-designer-control'));
console.log(obj);

The result would be objects in objects in objects etc. If only 2 lays of LI exist, the second layer objects will always be empty (that's alright). It's build to be recursive though: 3 layers, 4 layers etc, no problem.

edit
Tweaked it a little: http://jsfiddle.net/rudiedirkx/xhLwF/

edit
Result in Chrome 10:

Object
  1: Object (empty)
  2: Object >
    4: Object (empty)

edit
Stringified JSON result:

{"1": {}, "2": {"4": {}}}


You must use objects to do this:

var dom = {
   "2":[4]
   ,
   "1":[]
};

I´m not sure if this is the answer to your question :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜