<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>创建一个虚拟DOM实例</title> <style> .list{ color:green; font-size: 30px; } </style> </head> <body> <script> function Element(obj) { this.tagName = obj.tagName; this.props = obj.props || {}; this.children = obj.children || []; } Element.prototype.render = function () { var el = document.createElement(this.tagName); var props = this.props; for (propName in props) { propValue = props[propName]; el.setAttribute(propName, propValue); } this.children.forEach(function (child) { var elemChild = null; if (child instanceof Element) { elemChild = child.render(); } else { elemChild = document.createTextNode(child); } el.appendChild(elemChild); }); return el; }; var elem = new Element({ tagName: 'ul', props: { 'class': 'list' }, children: [ new Element({ tagName: 'li', children: ['list1'] }), new Element({ tagName: 'li', children: ['list2'] }) ] }); document.querySelector('body').appendChild(elem.render()); </script> </body> </html>
216、虚拟DOM模拟
猜你喜欢
转载自www.cnblogs.com/gushixianqiancheng/p/13204353.html
今日推荐
周排行