preface

The year 2022 is almost here and jQuery is out of date, so do we still need to learn jQuery?

I think so, because there are a lot of programming conventions in jQuery, and we should learn some of the ideas of jQuery as a transition to better understand more complex frameworks like Vue and React

Design idea

As we know, the basic design idea and main usage of jQuery is to “select a web element and do something with it”. To expand, provide a function that takes a selector (or array), retrieves elements based on that selector, and returns an object (called an API) that has methods to manipulate those elements.

With this in mind, we can simply write a beggar version of jQuery

window$=window.jQuery = function(selectorOrArray){
    let elements
    if(typeof selectorOrArray ==='string'){
        elements = document.querySelectorAll(selectorOrArray)
    }else if(selectorOrArray instanceof Array){
        elements  = selectorOrArray
    }
    let api = {
        addClass(className){
            for(let i=0; i<elements.length; i++){ elements[i].classList.add(className) }return this
        },
        find(selector){
            let array = []
            for(let i=0; i<elements.length; i++){const elements2 = Array.from(elements[i].querySelectorAll(selector))// Create a new elements2 equal to an array of iterated elements
               array = array.concat(elements2)// Put elements2 into an empty array
            }
            array.oldApi = this / / this is the old API, this oldApi just in array, so you need to add oldApi: selectorOrArray. OldApi, it can be placed in the selector or an array
            return jQuery(array)// Create an Api object and make jQuery accept an array. The new Api will manipulate the array
        },
        oldApi:selectorOrArray.oldApi,
        end(){... },each(fn){... }}return api
}
Copy the code

This brief snippet of code alone illustrates two of the core design ideas of jQuery

closure

The addClass and find functions here access the external variable elements, which has the benefit of: The user can never operate on Elements directly, but only with a function. As long as the function does not die, elements will not die, because the function is accessing elements and cannot delete it

Chain calls

Return this from addClass (this is the API);

$('div').find('h3').eq(2).html('Hello');
// Find all the div elements, find the h3 tag in the div element, select the third h3 tag, replace the text content
Copy the code

As you can see, this method of chaining calls is called chaining calls. The next time a function is called, the new function contains the value returned by the previous function, so it can chaining different operations together

$('div') .find('h3'). Eq. (2). The 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

JQuery has many other design ideas, such as:

getter/setter

$('h1').html(); // HTML () takes no arguments to fetch the value of h1$('h1').html('Hello'); // HTML () takes the argument Hello, which assigns h1
Copy the code

overloading

Using function overloading, a function can handle multiple arguments at the same time. For example, the argument to $() cannot be a selector or an HTML tag

$('.red'The $()'< div > < span > hello < span > < / div >')
Copy the code

For other design ideas, please see Ruan Yifeng’s blog: jQuery Design Ideas

Learning these design ideas can give us a lot of programming skills that will help us build our own wheels, rather than just call on other libraries or frameworks to provide functionality

The common API

Access to elements

Expressions can be CSS selectors:

  • $(document)Select the entire document object
  • $('#myId')Select the page element with ID myId
  • $('div.myClass')Select the div element whose class is myClass
  • $('input[name=first]')Select the input element whose name attribute is equal to first
  • .

They can also be jquery-specific expressions

  • $('a:first')Select the first A element in the web page
  • $('tr:odd')Select the odd-numbered rows of the table
  • $('#myForm :input')Select the input element in the form
  • $('div:visible')Select the visible div element
  • .

increase

  • $('.inner').append('<p>Test</p>')
    • Add a p tag at the end of all elements whose class is inner to add the last child
  • $('<p>Test</p>').appendTo('.inner')
    • The function is the same as append, but the syntax order is different
  • $('.inner').prepend('<p>Test</p>')
    • Add a p tag to the front of all elements whose class is inner
  • $('<p>Test</p>').prependTo('.inner')
    • Prepend is the same as prepend, but has a different syntax
  • $('<div/>').after('<p>Test</p>')and$('<p>Test</p>').insertAfter('.inner')
    • Same as Append and appendTo
  • ('<div/>').before('<p>Test</p>')and$('<p>Test</p>').insertBefore('.inner')
    • Prepend,prepend,prepend

delete

  • $('.hello').empty()
    • Delete all child nodes whose class is Hello
  • $('.hello').remove()
    • Delete the element whose class is Hello. If hello contains child nodes, the child nodes will also be removed
  • $('div').remove('.hello')
    • Add an optional selector argument to filter matched elements and remove elements in div whose class is Hello

Change and check

  • $('div').insertAfter($('p'))

    • If div and p are existing elements, this method moves div after P
    • $('p').after($('div'))You can also do this
    • The difference is that they return different elements. The first one returns div, the second one returns P
    • Similarly, any API in the increment operation can implement this movement function
  • Read and write the content

$('h1').html(); // HTML () takes no arguments to fetch the value of h1$('h1').html('Hello'); // HTML () takes the argument Hello, which assigns h1
Copy the code

Similarly, the value and assignment functions are:

.html() retrieves or sets the HTML content.text () retrieves or sets the text content.attr () retrieves or sets the value of an attribute......Copy the code
  • Read and write CSS
/ / read
$(div).css("background-color"$(div).css(["width"."height"."color"."background-color"]) reads multiple attribute values of div/ / write
$(div).css("color"."red"Change the div color to $(div).css({'background-color' : 'yellow'.'font-weight' : 'bolder'}) changes multiple attribute values of divCopy the code
  • $(div).on('click', fn)
    • Add a listener event named click to div
  • $(div).off('click', fn)
    • Delete the listener event

For full API, please refer to jQuery_API Chinese documentation