原生js实现一个简化版的h函数
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body></body>
<script>javascript">//基本内容const h = (tag, attrs, content) => {const el = document.createElement(tag)if(attrs instanceof Object){Object.keys(attrs).map((key)=>{if(/^on[A-Z]/.test(key)){//事件el.addEventListener(key.slice(2).toLocaleLowerCase(), attrs[key])}else if(key=='class'){//类名el.className = attrs[key]}else if(key=='style'){//标签行内样式el.style[key] = attrs[key]}else if(key=='color'){//标签行内样式el.style.color = attrs[key]}else{el[key] = attrs[key]}})}if(Array.isArray(content)){content.map(item=>el.append(item))}else if(content!=null){el.append(content)}document.body.append(el)return el}//调用h函数h('div', {color: 'red', class: 'h-div'}, 'hello world')h('div', null, [h('button', {onClick:function(){//这里是按钮事件的处理console.log('点击')}}, '点击按钮')])</script>
</html>