우리만의 선택자 라이브러리를 만들어 봅시다.

8789 단어 webdevhtmljavascript

기본 프레임워크:




<!DOCTYPE html>
<html lang=de>
  <meta charset=UTF-8>
  <title>myDemo</title>
  <style>
    .blue{
      color:blue;
    }
    .pointer{
      cursor:pointer;
    }
  </style>
  <h1>Selector</h1>
  <p>lorem 1</p>
  <p>lorem 2</p>
<script> 
"use strict";
const $ = function ( selector = null ) {
  class selection {
    constructor( selector ) {    
      if ( selector ) {
        this.nodes =
         selector === document ? [document] :
         selector === window ? [window] :
         selector.nodeType ? [selector] :
         selector.constructor.name==this.constructor.name ? selector.nodes :
         NodeList.prototype.isPrototypeOf( selector ) ? selector :
         document.querySelectorAll( selector )
         this.toNode=this.nodes[0] 
      }
    }

    each = callback => ( this.nodes.
      forEach( ( _node, index ) => 
        callback( _node, index )
      ), this)

    addClass = ( ...classes ) => this
      .each( _node =>
        _node.classList.add( ...classes ) )

    removeClass = ( ...classes ) => this
      .each( _node =>
        _node.classList.remove( ...classes ) )

    click = callBack => this
      .each( ( _node ) => _node
      .addEventListener( 'click' , callBack ) )

  }
  return selector = new selection( selector )
}

$( 'p' )
  .addClass( 'blue', 'red' )
  .addClass( 'white' )
  .removeClass( 'white', 'red' )
  .click( ( el ) => console.log(
    el.currentTarget.textContent
  ))
  .addClass( 'pointer' )

</script>


주석에 확장에 대한 제안 및 코드를 작성하십시오.

좋은 웹페이지 즐겨찾기