Input “selector” to output the API object that can manipulate web elements

  • The basic design idea and usage of jQuery is to “select a web element and do something with it”.
  • JQuery (selector) is used to get the corresponding elements, but it does not return them,
  • Instead, it returns an object, called an API, that directly manipulates the corresponding element
  • Next, we’ll write a simple window.jquery by hand
window.jQuery = function(selectorOrArrayOrTemplate) {
    let elements
    if(typeof selectorOrArray === 'string') {// The HTML tag is passed in
        elements = document.querySelectorAll(selectorOrArray)
    }else if(selectorOrArray instanceof Array) {// Pass in an array
        elements = selectorOrArray
    }

    //elements are elements or nodes to operate on

    let api = {
        // The following functions operate elements
        find(selector){
            let array = []
            for(let i =0; i<elements.length; i++){const elements2 = Array.from(elements[i].querySelectorAll(selector)) array.push(... elements2) } array.oldApi =this // This is the old API
            return jQuery(array)
        },
        appendTo(selector){},addClass(className){},end(className){}}return api
}
Copy the code

Second, chain call

One of the dark arts of jQuery is its support for chained calls, i.e

$('div')
  .find('h3')
  .addClass('red')
  .text('Hi, I'm new.');
// Find all div elements, find the h3 tag in all div elements, add the 'red' class to the h3 tag, and replace the text content
Copy the code

This is possible because jQuery(Selector) returns an API that manipulates the selected element

JQuery also provides the end method, which allows the result set to take a step back:

$('div') .find('h3') .eq(2) .html('Hello'). The end ()// Go back to the step where all h3 elements are selected.eq(0) // Select the first h3 element.html('World'); // Change its content to World
Copy the code

Getter, setter design pattern

The third design idea of jQuery is to use the same function for getters and setters. It depends on the parameters of the function, which is an overload of the function.

Use function overloading

  • With function overloading, a function can handle multiple arguments simultaneously
  • For example, the argument to $() can be not only a selector, but also an HTML tag
$('.red'The $()'
      
hahaha
'
) $(Array of elements)Copy the code

How does this work? And the answer is by overloading the function, write a different if else

window.jQuery = function(selectorOrArrayOrTemplate){
  let elements
  if(typeof selectorOrArrayOrTemplate === 'string') {if(selectorOrArrayOrTemplate.trim().indexOf('<') = = =0) {The string is coming from the / / HTML tags, such as $(' < div > < span > ha ha ha ha < span > < / div > '),
      // So we need to create the corresponding HTML tag, and then return
      elements=[createElement(selectorOrArrayOrTemplate)]
    }else{
      // find div such as $('.red')
      elements = document.querySelectorAll(selectorOrArrayOrTemplate)
    }
  }else if(selectorOrArrayOrTemplate instanceof Array) {// An array of nodes is passed in, so assign to elements to begin processing
    elements = selectorOrArrayOrTemplate
  }

  function createElement(string){
    const container = document.createElement("template");
    container.innerHTML = string.trim();
    return container.content.firstChild;
  }
  
  // The API can operate on elements
  let api = {
    addClass(className){},
    find(selector){},
    each(){}}return api
Copy the code

5. Common APIS

increase

  • $(‘div’).append(jQuery object) Adds an element in the last position of the child element of the div
  • $(‘<h2>Ha, ha, ha</h2>AppendTo (selector/jQuery object) adds “hahaha” from the end of the child element of the selector selected.
  • $(‘div‘).prepend(‘h2‘) in all the children of div, insert h2 from the beginning
  • And similarly
    ( h 2 ) . p r e p e n d T o ( (‘`h2`’).prependTo(
    (‘div‘))
  • (‘`#test`’).after(div) And a brother
  • (‘`#test`’).before(div) And a brother

delete

  • $div.remove()
  • $div.empty()

Change and check

  • $div.text(?) Reading and writing text content
  • $div.html(?) Reading and writing HTML content
  • $div.css({‘color’: ‘red’}) reads and writes CSS
  • $div.on(‘click’, fn)
  • $div.off(‘click’, fn)

Implement a simple jQuery

Goal:

<div id=test>
  <div class=child>1</div>
  <div class=child>2</div>
  <div class=child>3</div>
</div>
Copy the code
window.jQuery = function(Please fill the whole){please completionreturn {
    addClass(){please complete},find()}}}window$=window.jQuery

$('#test').find('.child').addClass('red') // Please make sure this sentence is executed successfully
Copy the code

$(‘#test’).find(‘.child’).addclass (‘red’) $(‘#test’).find(‘.child’).addclass (‘red’

window.jQuery = function(selectorOrArray) {
    let elements
    if(typeof selectorOrArray === 'string'){
        elements = document.querySelectorAll(selectorOrArray)
    }else if(selectorOrArray instanceof Array){
        elements = selectorOrArray
    }

    //elements are elements or nodes to operate on

    let api = {
        // The following functions operate elements
        / / $(' # test). The find (' child '). The addClass () 'red' / / please make sure that this sentence executed successfully
        find(selector){
           let resultArr = []
            for (let i = 0; i < elements.length; i++) {
                letchildElements = elements[i].querySelectorAll(selector) resultArr.push(... childElements) }return jQuery(resultArr)
        },
        addClass(className) {
            this.each.call(this.(n) = >n.classList.add(className))
            return this
        },
        each(fn){
            for (let i = 0; i < elements.length; i++) {               
                fn(elements[i])
            }
            return this}}return api
}

window$=window.jQuery

$('#test').find('.child').addClass('red') // Please make sure this sentence is executed successfully
Copy the code

Preview links: js.jirengu.com/xohirivawe/… Reference data: www.ruanyifeng.com/blog/2011/0… www.jquery123.com/