实现一个jQuery的API

实现一个jQuery的API

主要实现以下的功能

  1. 给元素增加class
  2. 给对应的元素设置文本

实现过程

  1. 首先声明一个函数jQuery()封装要实现上面功能的函数
  2. 在jQuery()函数中声明一个对象nodes,这个对象中有两个函数,这两个函数分别是实现上面的两个功能
  3. 当调用函数jQuery()的时候,在函数中判断传递的参数是字符串还是节点,然后对不同的数据类型做出不同的处理
  4. 接着就是在对象nodes中用不同的函数实现不同的功能
  5. 然后jQuery()函数会返回对象nodes,从而可以在函数外面调用函数里面的对象中的方法

实现代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>
<body>
    <div>选项1</div>
    <div>选项2</div>
    <div>选项3</div>
    <div>选项4</div>
    <div>选项5</div>
    <script>
        window.jQuery=function(nodeOrSelector){
            let nodes={}
            let node1=[]
            if(typeof nodeOrSelector==='string'){
               let temp=document.querySelectorAll(nodeOrSelector)
               for(let i=0;i<temp.length;i++){
                   node1[i]=temp[i]
               }
            //    node1.length=temp.length
            }else if(nodeOrSelector instanceof Node){
                node1={
                    0:nodeOrSelector,
                    length:1
                }
            }
            nodes.addClass=function(classes){
                classes.forEach(value => {
                    for(let i=0;i<node1.length;i++){
                        node1[i].classList.add(value)
                    }
                })
            //  console.log(Array.isArray(node1))
            }

             nodes.setText=function(text){
                for(let i=0;i<node1.length;i++){
                    node1[i].textContent=text
                }
            }
            return nodes
            
           
        }
        window.$=jQuery
        var $div=$('div')
        $div.addClass(['red'])
        $div.setText('hi')
      

    </script>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。