原生js实现一个简化版的h函数

原生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>
    //基本内容
    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>
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容