题目
请补全JavaScript代码,要求将对象参数转换为真实的DOM结构并返回。
注意:
1. tag为标签名称、props为属性、children为子元素、text为标签内容
编辑
核心代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>虚拟dom</title> </head> <body> <!-- 析构对象参数中的tag、props、children、text值 当tag的数据类型为”string“时,通过tag标签创建新节点并且挂载在vnode对象参数的el属性上 再通过setAttribute函数给vnode.el节点设置属性 然后通过appendChild、createTextNode将当前节点对象的text内容插入vnode.el节点上 最后通过createElm函数递归children数组重复以上过程 当tag的数据类型不为string时,直接通过createTextNode创建文本节点 --> <script>var vnode = { tag: 'ul', props: { class: 'list' }, text: '', children: [{ tag: "li", props: { class: "item" }, text: '', children: [{ tag: undefined, props: {}, text: '牛客网', children: [] }] }, { tag: "li", props: {}, text: '', children: [{ tag: undefined, props: {}, text: 'nowcoder', children: [] }] } ] } const _createElm = vnode => { let { tag, props, children, text } = vnode if (typeof tag == "string") { vnode.el = document.createElement(tag) _setAttr(vnode.el, props) vnode.el.appendChild(document.createTextNode(text)) children.forEach(child { vnode.el.appendChild(_createElm(child)) }) } else { vnode.el = document.createTextNode(text) } return vnode.el } const _setAttr = (elem, attrs) => { for (key in attrs) { elem.setAttribute(key, attrs[key]) } } </script> </body> </html>
总结
析构对象参数中的tag、props、children、text值
当tag的数据类型为”string“时,通过tag标签创建新节点并且挂载在vnode对象参数的el属性上
再通过setAttribute函数给vnode.el节点设置属性
然后通过appendChild、createTextNode将当前节点对象的text内容插入vnode.el节点上
最后通过createElm函数递归children数组重复以上过程
当tag的数据类型不为string时,直接通过createTextNode创建文本节点