1. 程式人生 > 實用技巧 >216、虛擬DOM模擬

216、虛擬DOM模擬

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>建立一個虛擬DOM例項</title>
</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; var propName = this.propName; var propValue = this.propValue; 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(); } 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>