下面的例子则是利用get拦截,实现一个生成各种 DOM 节点的通用函数dom。文章来源:https://www.toymoban.com/news/detail-692543.html
<body>
</body>
<script>
const dom = new Proxy({}, {
get(target, property) {
return function(attrs = {}, ...children) {
const el = document.createElement(property);
for (let prop of Object.keys(attrs)) {
el.setAttribute(prop, attrs[prop]);
}
for (let child of children) {
if (typeof child === 'string') {
child = document.createTextNode(child);
}
el.appendChild(child);
}
return el;
}
}
});
const el = dom.div({},
'Hi, my name is ',
dom.a({href: 'https://blog.csdn.net/qq_22744093?type=blog'}, 'kexuexiong'),
'. I like:',
dom.ul({},
dom.li({}, 'The web'),
dom.li({}, 'Food'),
dom.li({}, '…actually that\'s it')
)
);
document.body.appendChild(el);
</script>
输出结果:
文章来源地址https://www.toymoban.com/news/detail-692543.html
到了这里,关于【ES6】Proxy的高级用法,实现一个生成各种 DOM 节点的通用函数dom的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!