实现一个 jQuery 的 API

2017-12-30  本文已影响0人  张镕凡

思路

<!DOCTYPE html>
<html>
    <head>
        <meta charset="{CHARSET}">
        <title></title>
        <style>
          .red{color: red;}
        </style>
        
    </head>
    <body>
      <div>11</div>
      <div>11</div>
      <div>11</div>
      <div>11</div>
      <script>
      window.jQuery = function(nodeOrSelector){
        let nodes = {}
        if(typeof nodeOrSelector === 'string'){
          let temp = document.querySelectorAll(nodeOrSelector)
          for(let i = 0; i < temp.length;i++){
            nodes[i] = temp[i]
          }
          nodes.length = temp.length
        }else if(nodeOrSelector instanceof Node){
          nodes = {
            0:nodeOrSelector,
            length:1
          }
        }
        nodes.addClass = function(classes){
          classes.forEach((value)=> {
            for (let i = 0;i<nodes.length;i++){
              nodes[i].classList.add(value)
            }
          })
        }
        
        
        nodes.setText = function(classes){
          classes.forEach((value)=> {
            for (let i = 0;i<nodes.length;i++){
              nodes[i].textContent = value
            }
          })
        }
        return nodes
      }
      window.$ = jQuery
      
      
    </script>
    </body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读