function Element(tagName, props, children) {
this.tagName = tagName;
this.props = props;
this.children = children;
}
Element.prototype.render = function() {
// 创建元素
var element = document.createElement(this.tagName);
// 获取属性
var props = this.props;
for (let propName in props) {
let propValue = props[propName];
// 挂载元素属性
element.setAttribute(propName, propValue);
}
// 获取子节点
var children = this.children || [];
children.forEach((child) => {
// 遍历子节点是否为文字节点
var childElement = (child instanceof Element) ? child.render() : document.createTextNode(child);
element.appendChild(childElement);
});
// 返回创建元素
return element;
};
// 创建实例
var ul = new Element(
'ul', {
id: 'list'
}, [
new Element(
'li', {
class: 'list-item'
}, ['item-1']
),
new Element(
'li', {
class: 'list-item'
}, ['item-1']
),
new Element(
'li', {
class: 'list-item'
}, ['item-1']
),
new Element(
'li', {
class: 'list-item'
}, ['item-1']
),
]
);
// 创建真实 DOM
var rootElement = ul.render();
// 将 DOM 挂载到 body 上
document.body.appendChild(rootElement);
网友评论