美文网首页
jQuery引入细节

jQuery引入细节

作者: sean_lau | 来源:发表于2019-08-22 00:19 被阅读0次

    题目:按照课程内容,补全下面的代码,并记录实现过程

    window.jQuery = ???
    window.$ = jQuery
    var $div = $('div')
    $div.addClass('red') // 可将所有 div 的 class 添加一个 red
    $div.setText('hi') // 可将所有 div 的 textContent 变为 hi
    

    完整代码:

    HTML
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
    </head>
    <body>
    <div class="div"></div>
    <div class="div"></div>
    <div class="div"></div>
    </ul>
    </body>
    </html>
    
    CSS
    .div.red{
      background:red;
    }
    .div{
      width:30px;
      height:30px;
      border:2px solid black;
      background:blue;
      border-radius:50%;
      text-align:center;
    }
    
    
    JS
    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) {
      if (classes instanceof Array) {
        classes.forEach((value) => {
        for (let i = 0; i < nodes.length; i++) {
            nodes[i].classList.add(value)
          }
         })
       } else if (typeof classes === 'string') {
        for (let i = 0; i < nodes.length; i++) {
         nodes[i].classList.add(classes)
        }
       }
    }
      nodes.setText=function(text){
         for(let i=0;i<nodes.length;i++){
           nodes[i].textContent=text
         }   
      }
    return nodes
    }
    window.$ = jQuery
    var $div=$('div')
    $div.addClass('red')
    $div.setText('hi')
    

    细节记录:

    https://www.jianshu.com/p/804ac714e288

    相关文章

      网友评论

          本文标题:jQuery引入细节

          本文链接:https://www.haomeiwen.com/subject/qmowsctx.html