jquery无限级创建DOM节点
代码实现:
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>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步