Niu X's jQuery

Niu X's jQuery

How awesome is jQuery?

  • jQuery was released in 2006 and is by far the longest-lived library for the front end. It is also the most widely used library in the world, 80% of the top 100,000 websites in the world are still using jQuery
  • This is the jQuery usage data as of March of this year

Why is jQuery so awesome?

Let's take a look at the most notable features of jQuery first
  • Easy to use

    How simple is it? for example:

    • If Query is not used, JS event listener (compatible with IE6) should be written like this
    if (button.addEventListener) button.addEventListener( 'click' ,fn); else if (button.attachEvent) { button.attachEvent( 'onclick' , fn); } else { button.onclick = fn; } Copy code
    • But if you use jQuery, you only need to write
    $ (Button) .on ( 'the Click' , Fn) copy the code
    • If you want to get all the elements corresponding to .nav> .navItem, use jQuery like this
    $( '.nav> .navItem' ) Copy code
    • On IE 6, you have to write this
    var navItems = document .getElementsByClassName( 'navItem' ) var result = [] for ( var i = 0 ; i <navItems.length; i++){ if (navItems[i].parentNode.className.match( /\bnav\b/ ){ result.push(navItems[i]) } } Copy code
  • It solves the problem of dom api compatibility and makes dom operation easier

  • It supports selection of components in a way similar to css selectors

  • Support batch operation of elements in the array, also called implicit iteration

  • Support chain operation, can complete very complex logic in one sentence

  • There is an easy-to-use plug-in extension mechanism

  • The deffered asynchronous scheme is earlier than the promise.

Is jQuery obsolete?

  • Since the past few years, almost no new projects will use jQuery to develop; even if there is, it is not worth showing off.
  • jQuery solves many front-end technical pain points, and its impact on the front-end is unprecedented. But with the development of the front-end, jQuery has also entered an outdated state, and it has solved the pain points for us with better alternatives.
  • Although jQuery is outdated, jQuery is still an essential skill for front-end development. For a front-end newcomer, this pit must be stepped on.

jQuery design ideas

  1. jQuery entry function

    • Wait for the page DOM to be loaded before executing JS, traditional way of writing
    $( document ).ready( function () {} JQueryCode) copy the code
    • A more concise way of writing, equivalent to DOMContentLoaded in native JS
    $( function () {} JQueryCode) copy the code
  2. jQuery top-level object

    $

    • $
      In fact, it is another name for JQuery, you can use jQuery instead in the code
      $
      , but
      $
      It's simpler.

    • $
      It is the top-level object in jQuery, equivalent to the window in native JS, using elements
      $
      Wrapped into a jQuery object.

  3. jQuery object and DOM object

    • DOM object: elements obtained with native JS
    var myDiv = document .querySelector( 'div' ); Copy code
    • jQuery object: the object obtained by jQuery, its essence is through
      $
      The element object is wrapped and stored in the form of a pseudo-array
    $( 'div' ); Copy code
    • jQuery objects can only use jQuery methods, while DOM objects can only use native JS attributes and methods. They can be converted to each other

      Convert DOM objects to jQuery objects:

      $(DOM object);

      Convert Query object to DOM object:

    $ ( 'Div' ) .get (index); //index is the index number //or $ ( 'div' ) [index]; duplicated code
  4. Select web page element

    • The basic design idea and main usage of jQuery is to "select a certain web page element, and then perform certain operations on it". This is the fundamental feature that distinguishes it from other Javascript libraries.
    • The selection expression can be a CSS selector:
    $( document ) //Select the entire document object $( '#myId' ) //Select the webpage element whose ID is myId $( 'div.myClass' ) //Select the div element whose class is myClass $( 'input[name= first] ' ) //select the name attribute of the first input element is equal to copy the code
    • It can also be an expression specific to jQuery:
    $( 'a:first' ) //Select the first a element in the webpage $( 'tr:odd' ) //Select the odd rows of the form $( '#myForm :input' ) //Select the input element in the form $( 'div:visible' ) //Select visible div elements $( 'div:gt(2)' ) //Select all div elements, except the first three $( 'div:animated' ) //Select the current Copy the code of the animated div element
  5. Change the result set

    • jQuery Design Idea: Provide a variety of powerful filters to filter the result set and narrow the selection results.
    $( 'div' ).has( 'p' ); //select the div element that contains the p element $( 'div' ).not( '.myClass' ); //select the div element whose class is not equal to myClass $( 'div' ).filter( '.myClass' ); //Select the div element whose class is equal to myClass $( 'div' ).first(); //Select the first div element $( 'div' ).eq( 5 ); //Select the 6th div element to copy the code
    • Sometimes, we need to start from the result set and move to nearby related elements. jQuery also provides a method of moving on the DOM tree:
    $( 'div' ).next( 'p' ); //Select the first p element behind the div element $( 'div' ).parent(); //Select the parent element of the div element $( 'div' ).closest( 'form' ); //Select the parent element of the form closest to the div $( 'div' ).children(); //Select all child elements of the div $( 'div' ).siblings(); //Select sibling elements of div Copy code
  6. Chain call

    • This is the most commendable and convenient feature of jQuery. Its principle is that each step of the jQuery operation returns a jQuery object, so different operations can be linked together.
    • jQuery also provides the .end() method, which allows the result set to go back one step:
    $( 'div' ) .find( 'h3' ) .eq( 2 ) .html( 'Hello' ) .end () //return to select all of the elements that step h3 .EQ ( 0 ) //Select the first h3 element .html ( 'World' ); //read its contents World Copy the code
  7. Style operation

    • Basic way
    /* $(function() { $('Selector').css('Properties','Value'); }) */ $ ( '.Current' ) .css ( 'the backgroundColor' , 'Red' ); duplicated code
    • Implicit iteration
    • jQuery will store the acquired elements in the form of a pseudo-array, and at the same time loop through all the matched elements, instead of manually traversing them. This internal traversal execution process is called implicit iteration.
    • jQuery exclusive thinking, using implicit iteration, eliminating the for loop, and then using siblings to find sibling nodes but does not include its own characteristics
    $(element).click( function () { $( this ).css( 'styleCode' , 'style' ); $( this ).siblings().css( 'styleCode' , '' ); }) Copy code
  8. Element operation

    • jQuery design idea: Use the same function to complete the getter and setter, that is, the "evaluator" and the "evaluator" are integrated. Whether to take a value or assign a value depends on the parameters of the function.
    $( 'h1' ).html(); //html() has no parameters, which means that the value of h1 is taken out $ ( 'H1' ) .html ( 'the Hello' ); //HTML () with a parameter Hello, h1 represents the assignment of duplicated code
    • Common value and assignment functions are as follows:
    .html() Get or set html content .text() Get or set text content .attr() Get or set the value of an attribute .width() Get or set the width of an element .height() Get or set the height of an element .val() Get the value of a form element Copy code
    • It should be noted that if the result set contains multiple elements, then when assigning, it will assign values to all of the elements; when assigning values, only the value of the first element is taken out (except for .text(), which takes out The text content of all elements).

    • Iterate over elements

      jQuery implicit iteration is to do the same operation on the same type of element. If you want to do different operations on the same type of element, you need to use traversal

      The each() method traverses the elements:

      $ ( "Div" ) .each ( function ( index, DOMEle ) {} jQueryCode) copy the code
    • index: index number

      DOMEle: Each DOM element is not a jQuery object. You must use the $ package before using the jQuery method, otherwise you can only use the native JS method.

    • The $.each() method traverses the elements:

    var arr = [ 1 , 2 , 3 ]; $.each(arr, function ( index, value ) { jQueryCode }) Copy code
    • The $.each() method can be used to traverse any object, mainly used to process data, such as traversing an array, object index is also an index (when traversing an object, index is the key), and value is the content (value) to be traversed

  9. Element operation: move

    • jQuery Design Idea: Provides two sets of methods to manipulate the position of elements in the web page. One set of methods is to move the element directly, and the other set of methods is to move other elements so that the target element reaches the position we want.

      Suppose we select a div element and need to move it behind the p element.

      The first method is to use .insertAfter() to move the div element behind the p element:

    $( 'div' ).insertAfter($( 'p' )); Copy code
    • The second method is to use .after() to add the p element to the front of the div element:
    $( 'p' ).after($( 'div' )); Copy code
    • On the surface, the effects of these two methods are the same, and the only difference seems to be the difference in the operating angle of view. But in fact, they have a major difference, that is, the returned elements are different. The first method returns the div element, and the second method returns the p element. You can choose which method to use according to your needs.

    • There are four pairs of operating methods using this mode:

    .insertAfter() and .after(): //Insert the element from the back outside of the existing element. insertBefore() and .before(): //Insert the element from the front outside of the existing element.appendTo() and. append(): //In the existing element, insert the element from the back. prependTo() and .prepend(): //In the existing element, insert the element from the front copy code
  10. Operation of elements: copy, delete and create

    • In addition to moving the position of elements, jQuery also provides several other important methods for manipulating elements. Use .clone() to copy elements. Remove elements using .remove() and .detach(). The difference between the two is that the former does not retain the event of the deleted element, while the latter retains it, which is useful for reinserting the document.

      Empty the content of an element (but not delete the element) using .empty().

      The method of creating a new element is very simple, just pass the new element directly into the jQuery constructor:

    $( '<p>Hello</p>' ); $( '<li class="new">new list item</li>' ); $( 'ul' ).append( '<li>list item</li>' ); Copy code
    //Create elements: var li = $ ( "<li> </li>" ); //create a label li duplicated code
    //Add element: $( "ul" ).append(li); //The added element inside is at the end of the ul internal element $( "ul" ).prepend(li); // Copy the code at the top
    var div = $( "<div></div>" ); $( "div" ).before(div); //The externally added element is in front of the target element div $( "div" ).after(div); // Copy the code behind the target element
    Remove elements: $( "div" ).remove(); //delete the specified element div itself $( "ul" ).empty(); //delete all child nodes in the specified element $( "ul" ).html( "" ) ; //Clear the contents of the specified elements, substantially equivalent empty copy the code
  11. Size and position operation

    • jQuery size: the return value is all numeric, without unit
    width()/height() get the width and height of the element innerWidth()/innerHeight() gets the width and height of the element containing padding outerWidth()/outerHeight() Get the width and height of the element including padding and border outerWidth(true)/outerHeight(true) Get the width and height of the element including padding, border, and margin If the above parameter is empty, the corresponding value will be returned. If the parameter is a number, the corresponding value will be modified Copy code
    • jQuery location:

    offset() Set the offset coordinates of the retrieved element relative to the document, which has nothing to do with the parent

    //Obtain: $(element).offset(); $(element).offset().top; $(element).offset().left; //set $ (Element) .offset ({ Top : 200 is , left : 300 }); duplicated code
    • position() Get the offset coordinates of the element with the positioned parent element. If the parent is not positioned, the document shall prevail. The position() method can only be obtained, not set
    //Obtain: $(element).position(); $(element).position().top; $(element).positon().left; Copy code

    scrollTop() and scrollLeft() set to get the head and left side of the scrolled element.

    //Get the scrolled head of the page $( document ).scrollTop(); //Set the scrolled head of the page $( document ).scrollTop( 100 ); Copy the code
  12. Tool method

    • jQuery Design Idea: In addition to operating on selected elements, it also provides some element-independent utility methods. These methods can be used directly without selecting the element.

    • If you understand the inheritance principle of the Javascript language, then you can understand the essence of the tool method. It is a method defined on the jQuery constructor, namely jQuery.method(), so it can be used directly. The methods for manipulating elements are methods defined on the prototype object of the constructor, that is, jQuery.prototype.method(), so they must be used after generating an instance (ie, selecting an element). If you don't understand this difference, the problem is not big, as long as you understand the tool method as a method that can be used directly like a javascript native function.

    • The commonly used tools and methods are as follows:

    $.trim() removes the spaces at both ends of the string. $.each() traverse an array or object. $.inArray() returns the index position of a value in the array. If the value is not in the array, -1 is returned. $.grep() returns the elements in the array that meet a certain standard. $.extend() merges multiple objects into the first object. $.makeArray() converts the object into an array. $.type() Determines the type of object (function object, date object, array object, regular object, etc.). $.isArray() Determines whether a parameter is an array. $.isEmptyObject() Determines whether an object is empty (does not contain any attributes). $.isFunction() Determines whether a parameter is a function. $.isPlainObject() Determines whether a parameter is an object created with "{}" or "new Object". $.support() Determines whether the browser supports a certain feature. Copy code
  13. Event operation

    • jQuery design idea: Bind events directly to web page elements.
    $( 'p' ).click( function () { alrt( 'Hello' ); }); Copy code
    • Currently, jQuery mainly supports the following events:
    .blur() The form element loses focus. .change() The value of the form element has changed .click() mouse click .dblclick() Double click with the mouse .focus() form element gets focus .focusin() Child element gets focus .focusout() child element loses focus .hover() Specify the processing function for mouseenter and mouseleave events at the same time .keydown() Press the keyboard (long key down, only return one event) .keypress() Press the keyboard (long keypress, multiple events will be returned) .keyup() Release the keyboard .load() element is loaded .mousedown() mouse down .mouseenter() mouse enter (enter the child element does not trigger) .mouseleave() Mouse leave (leave the child element without triggering) .mousemove() The mouse moves inside the element .mouseout() Mouse out (triggered when leaving the child element) .mouseover() Mouse enter (it is also triggered when entering the child element) .mouseup() release the mouse .ready() DOM loading is complete .resize() The size of the browser window has changed .scroll() The position of the scroll bar changes .select() The user selects the content in the text box .submit() User submission form .toggle() Run multiple functions in sequence according to the number of mouse clicks .unload() The user leaves the page Copy code
    • These events are all convenient ways of .bind() inside jQuery. Use .bind() to control events more flexibly, such as binding the same function to multiple events:
    $( 'input' ).bind( 'click change' , //bind click and change events at the same time function () { alrt( 'Hello' ); } ); Copy code
    • Sometimes, you only want the event to run once, then you can use the .one() method.
    $( "p" ).one( "click" , function () { alrt( "Hello" ); //Only run once, future clicks will not run }); Copy code
    • .unbind() is used to unbind the event.
    $( 'p' ).unbind( 'click' ); Copy code
    • On binding event syntax:
    element.on(events, [selector], fn); /* events: event type, one or more event strings separated by spaces, such as "click", "mouseenter" selector: the child element selector of the event-bound element fn: callback function*/ copy code
    //Event results are inconsistent $( ".demo" ) .on ({ mouseenter : function () { $( this ).css( "color" , "red" ); }, click : function () { $( this ).css( "background" , "skyblue" ); } }) //The event results are consistent $( ".demo" ) .on ( "mouseenter mouseout" , function () { $( this ).toggleClass( "csstyle" ); }) Copy code
    • on binding events to achieve event delegation
    $( "ul" ).on( "mouseover" , "li" , function () {JSCode }) Copy code
    • The on binding event realizes binding events to dynamically created elements in the future
    $( "ol" ).on( "click" , "li" , function () {alrt( "Hello" ); }) var li = $( "<li></li>" ); $( "ol" ).append(li); Copy code
    • The off() method can unbind event handlers bound by on()
    $( "div" ) .on ({ mouseenter : function () {alrt( "Mouse Passing Event" ) }, click : function () {alrt( "Mouse click event" )} }); $ ( "Div" ) .off (); //All unbundling $ ( "div" ) .off ( "the Click" ); //specified event unbundling copy the code
    • Shorthand for jQuery to automatically trigger events:
    //element. event(); $( "div" ).click(); copy code
    • trigger() method:
    $( "div" ).trigger( "click" ); Copy code
    • triggerHandler() method: This method does not trigger the default behavior of the element
    $( "div" ).triggerHandler( "click" ); Copy code
    • Properties and methods of jQuery event object
    event.pageX The horizontal distance between the mouse and the upper left corner of the webpage when the event occurs event.pageY When the event occurs, the vertical distance between the mouse and the upper left corner of the webpage event.type The type of event (such as click) event.which which key was pressed event.data binds data to the event object, and then passes in the event processing function event.target The web page element targeted by the event event.preventDefault() Prevents the default behavior of the event (for example, clicking a link will automatically open a new page) event.stopPropagation() Stop event bubbling to the upper element Copy code
    • In the event processing function, you can use the this keyword to return the DOM element targeted by the event:
    $( 'a' ).click( function ( e ) { if ($( this ).attr( 'href' ).match( 'evil' )) { //If it is confirmed as a harmful link e.preventDefault(); //Prevent opening $( this ).addClass( 'evil' ); //Add a harmful class } }); Copy code
  14. Special effect

    • Finally, jQuery allows objects to exhibit certain special effects.
    .fadeIn() fade in .fadeOut() fade out .fadeTo() adjust transparency .hide() hide elements .show() display element .slideDown() expand down .slideUp() roll up .slideToggle() Expand or roll up an element in turn .toggle() show or hide an element in turn Copy code
    • Except .show() and .hide(), the default execution time of all other special effects is 400ms (milliseconds), but you can change this setting.
    $ ( 'H1 of' ) .fadeIn ( 300 ); //300 ms fade $ ( 'h1 of' ) .fadeOut ( 'SLOW' ); //slowly fade copy the code
    • After the special effect is over, you can specify to execute a certain function.
    $( 'p' ).fadeOut( 300 , function () {$( this ).remove(); }); Copy code
    • More complex special effects can be customized with .animate().
    $( 'div' ).animate({ left : "+=50" , //Keep moving right opacity : 0.25 //Specify transparency }, 300 , //Duration function () { alrt( 'done!' ); }); //Callback function copy code
    • .stop() and .delay() are used to stop or delay the execution of special effects. $.fx.off If set to true, turn off all webpage special effects

Part of this article is excerpted from:

Fang Yinghang's personal webpage

jQuery Design Ideas-Ruan Yifeng