代码实现:
var data=[{"tag":"ul","attr":{"class":"ban_nav","id":"ban"}, "child":[ {"tag":"li", "child":[ {"tag":"a","attr":{"href":"activeNet.html","target":"_blank"}, "child":[ {"text":"第一个","tag":"span"}, {"text":"第二个","tag":"span"}, {"text":"第三个","tag":"span"}, ] }, {"tag":"a","attr":{"href":"activeNet.html","target":"_blank"}, "child":[ {"tag":"img","attr":{"src":"images/banner5.png"}}, {"tag":"img","attr":{"src":"images/banner5.png"}}, {"tag":"img","attr":{"src":"images/banner5.png"}} ] } ] }, {"tag":"li", "child":[ {"tag":"a","attr":{"href":"activeNet.html","target":"_blank"}, "child":[ {"tag":"img","attr":{"src":"images/activeNet/banner.png"}} ] } ] } ] }, {"tag":‘a‘} ] $(function(){ setData(‘banner‘,data); }) function setData(name,data){ var l=$(‘<span/>‘); createDOM(data,l) $(‘coder[name="‘+name+‘"]‘).html(l); } /* * 无限级创建DOM节点 * @param {Object} opt 参数对象 * @param {Object} parent 父级容器 */ function createDOM(opt,parent){ $.each(opt, function(k,v) { var _e={},l; /*存在内容时进行赋值,有些是没有的如:img*/ v[‘text‘] && (_e.text=v[‘text‘]); /*存在属性时进行赋值,以键/值配对出现*/ v[‘attr‘] && (_e=$.extend({},_e,v[‘attr‘])); /*创建dom节点*/ l=v.tag? $(‘<‘+v[‘tag‘]+‘/>‘,_e):v[‘text‘]; parent.append(l); /*存在子节点时,进行递归*/ if(v[‘child‘]){ createDOM(v[‘child‘],l); } }); }
html部分:
<coder name="banner"></coder>
时间: 2024-11-08 17:16:37