下面的例子則是利用get攔截,實現(xiàn)一個生成各種 DOM 節(jié)點的通用函數(shù)dom。文章來源:http://www.zghlxwxcb.cn/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>
輸出結果:文章來源地址http://www.zghlxwxcb.cn/news/detail-692543.html
到了這里,關于【ES6】Proxy的高級用法,實現(xiàn)一個生成各種 DOM 節(jié)點的通用函數(shù)dom的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!