jQuery usage notes

jQuery usage notes

jQuery basics

  1. jQuery introduction

  2. jQuery advantages

    • Open source, free, easy to learn
    • Good compatibility
    • Powerful selector
    • Chain operation
    • Convenient dom operation
    • Reliable event mechanism
    • Simple ajax
    • Rich animation and special effects plug-ins
    $( document ).ready( funtion () { $( "#box" ).html( "Hello" ).width( 400 ).height( 300 ).css( "border" , "1px solid #ccc" ).css( "padding" , "10px" ). append( "<p>Hello</p>" ); }) Copy code
  3. Get jQuery

    • Download the required version from the official website

    • Reference from the CDN server, such as www.bootcdn.cn/jquery

      < script src = "https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js" > </script > Copy the code
    • Run in npm

      npm install jquery
      Command automatic download

  4. jQuery version

    • jQuery 2.0 and above, not compatible with IE 8
    • Versions below jQuery 2.0 are compatible with IE 8
    • jQuery development version: jquery.js, with detailed annotations to help developers learn and understand
    • jQuery compressed version: jquery.min.js, compressed, small size, fast loading
  5. jQuery compatibility introduced

    <!--Conditional comments using IE browser--> <!--chrome, firefox, safari, opera, ie9 and above--> <!--[if gt IE 8]>--> < script src = "https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js" > </script > <!--<![endif]--> <!--ie8 and below--> <!--[if lte IE 8]> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <![endif]--> Copy code
  6. Use of jQuery

    //jQuery entry function $( document ).ready( function () { //code... }); $( function () { //code... }); Copy code

    $(document).ready() and window.onload have similar functions, but there are differences

    • ready is executed after the dom is drawn
    • onload is executed after the pictures and other external files are all loaded
  7. jQuery Dom object

    • querySelector("#box"): Native js dom object

    • $("#box"): jquery dom object, native methods cannot be used

    • Mutual conversion

      let jsBox = document .querySelector( "#box" ); $(jsBox).html( "Hello" ); //Use $(), js dom object -> jq dom object let jqBox=$( "#box" ); //What you get is a collection of dom objects jqBox [ 0 ] = .innerHTML "the Hello" ; //use [index], jq dom object -> js dom object duplicated code
  8. jQuery global object

    • jQuery, alias $
    • The function of $
      • The parameter is js dom object, convert it to jquery dom object
      • The parameter is the selector, get the jquery dom object
      • The parameter is
        <
        The tag at the beginning, to create an element, can be used
        appendTo
        Add to page

jQuery selector

  1. Basic selector

    $( "#box" ) //id selector selects the tag with id box $( ".item" ) //class selector selects the tag with class item $( "li" ) //tag name selector selects all li tags $ ( "*" ) //gloal selector selects all tags $( "li.item" ) //combo selector selects clss as item li tag $( "li,p" ) //multi selector selects all li and p tags to copy Code
  2. Level selector

    $( "ul li" ) //select li in the descendant element of ul $( "ul>li" ) //select li in the child element of ul $( "#item+li" ) //select the next sibling of #item Element $( "#item~li" ) //All sibling elements after selecting #item copy the code
  3. Filter selector

    $( "ul li:first" ) //select the first li tag in li $( "ul li:last" ) //select the last li tag in li $( "ul li:eq(i)" ) //Choose the i-th in li, starting from 0 $( "ul li:lt(i)" ) //Choose the one in li that is less than i, starting from 0 $( "ul li:gt(i)" ) //Select li that is greater than i, starting from 0 $( "ul li:odd" ) //Select elements in odd order, starting from 0 $( "ul li:even" ) //Select elements in even order, starting from 0 Start $( "ul li:not(.item)" ) //select elements in li whose class is not item $( ":header") //select all title tags $( ":focus") //get the focus of the selected element $ ( ": target" ) //url element selected anchor point, the anchor point may be a tag, id may be duplicated code
  4. Content selector

    $( "li:contains(str)" ) //Select the li tag that contains str $( "li:has(.item)" ) //Select the li tag that contains the descendant element of item $( "ul li :empty" ) //select li without content, innerHTML.length = 0 $( "ul li:parent" ) //select li with content (text or child element), innHTML.length != 0Copy code
  5. Visibility selector

    $ ( ": Visible" ) //select visual elements $ ( ": hidden" ) //Select Invisible Elements copy the code
  6. Attribute selector

    $( "img[alt]" ) //select the img tag with alt attribute $( "img[alt='str']" ) //select the img tag with alt ='str' $( "img[alt! ='str']" ) //Select the img tag with alt !='str' $( "img[alt^='s']" ) //Select the img tag with alt starting with s $( "img[ $ = alt 'r'] " ) //choose alt img tag ending r $ ( " img [alt] [title] " ) img tag having simultaneously selected//alt, title attribute copy the code
  7. Child element selector

    //-child sorts all sibling elements, starting from 1 $( "li:first-child" ) //selects the li tag that is li and ranks first in all sibling elements $( "li:last-child" ) //Choose the li tag that is li and the last li tag of all sibling elements $( "li:nth-child(i)" ) //Choose the li tag that is li and is the i-th li tag of all sibling elements $( "li :nth-last-child(i)" ) //Select li and rank the i-th li tag from the bottom of all sibling elements $( "li:only-child" ) //Select li tag without sibling elements //-of -type sorts the specified label elements, starting from 1 $( "li:first-of-type" ) //Select the li label that is li and ranks first in all siblings li $( "li:last-of-type " ) //Select the li label that is li and is the last li tag of all siblings li $( "li:nth-of-type(i)") //choose li and rank the i-th li label among all siblings li $( "li:nth-last-of-type(i)" ) //choose li and rank the i-th last sibling li the li tag $ ( "li: only-of-of the type" ) //choose can have siblings, but it is only a label element with the label li copy the code
  8. Form selector

    //Form control selector $( ":input" ) //Select all form controls input/select/textarea/button... $( ":text" ) //Select the text box $( ":password" ) //Select the password box $( ":radio" ) //Select the radio button $( ":checkbox" ) //Select the multi-select button $( ":file" ) //Select the text field $( ":submit" ) //Select input (type=submit), button (do not specify type or type=submit) $( ":reset" ) //select input (type=reset), button (type=reset) $( ":button") //select button, input (type=button) //form object selector $( ":disabled" ) //select unavailable elements $( ":enabled" ) //select available elements $( ":checked" ) //select radio and checkbox selected elements $( ":selected" ) //drop-down list to select the selected element copy the code

jQuery attributes and styles

  1. Attribute manipulation

    attr(attrName[,attrValue]) //Operate all attributes, including custom attributes prop(attrName[,attrValue]) //Operate compliant attributes removeAttr((attrName) //delete attributes removeProp((attrName) //delete Attribute added by prop() attr( "class" ,value) //Attribute setting hasClass(className) //Determine whether there is a corresponding class addClass(className) //Add class removeClass(className) //Remove class toggleClass(className) ) //Remove the class if it exists, add copy code if it doesn't

    for example

    < img id = "img-item" src = "" testAttr = "str" > </img > < script src = "/lib/jQuery-3.4.1.js" > </script > < script type = "text/javascript" > //Get attributes $( "#img-item" ).attr( "src" ); //Get src $( "#img-item" ).prop( "src" );//Get src $( "#img-item" ).attr( "testAttr" ); //Get testAttr $( "#img-item" ).prop( "testAttr" ); // Can not get non-compliant attributes, undefined //Set attributes $( "#img-item" ).attr ( "the src" , "..." ); //set the src $ ( "IMG-Item #" ) .prop ( "the src" , "..." ); //set the src </Script > copy the code
  2. Style operation

    //css css( "background-color" , "#ccc" ) //set or get css properties css({ "width" : "400px" , "height" : "200px" }) //set multiple css at once Property //Position offset() //Get or set the coordinate of the element in the document (top, left) position() //The coordinate of the element in the positioned ancestor element (top, left) srollTop() //Get or set Y scroll bar position scrollLeft() //get or set the X scroll bar position //size width(), height() //set or get the content size innerWidth(), innerHeight() //set or get the content size and padding and the outerWidth (), outHeight () //Sets or gets the size cassette copy the code
  3. Text manipulation

    html([str]) //Set or get html code, innerHTML text([str]) //Set or get text content, innerText val([str]) //Get or set text box, text field, equivalent to attr ("value") Copy code

jQuery filter

  1. filter

    //jq dom object function $( "ul li" ).first() //return the first jq dom object $( "ul li" ).last() //return the last jq dom object $( "ul li " ).eq(i) //Return the i-th jq dom object $( "ul li" ).not( ".itme" ) //After excluding objects satisfying class = item, return the set $( "ul li" ).filter( " .item " ) //Return a collection of objects that meet the condition of class = item $( "ul li" ).slice(a[,b]) //Return a to the last element or a to b (left Closed right open) object collection $( "ul li" ).has( '.item') //Returns the class object has child elements of the set item copy the code
  2. Find

    $( "ul" ).children([selector]) //select child elements that meet the conditions $( "ul" ).find( "li" ) //select child elements that meet the conditions $( "ul" ).parent ([selector]) //select the parent element that meets the condition $( "ul" ).parents([selector]) //select the ancestor element that meets the condition $( "ul" ).parentsUntil([selector]) //select All ancestor elements up to selector (not including selector) $( "ul" ).offsetParent() //Select the first positioned ancestor element, if not, select the html tag $( ".item" ).next([selector]) //Select the next sibling element that meets the conditions $( ".item" ).nextAll([selector]) //Select all sibling elements that meet the condition $( ".item").nextUntil([selector]) //Select all subsequent sibling elements until selector (not including selector) $( " .item " ).prev([selector]) //Select the previous sibling element that meets the conditions $( ". item" ).prevAll([selector]) //Select all the previous sibling elements that meet the condition $( " .item " ).prevUntil([selector]) //Select all the previous sibling elements until the selector (not including the selector) $( ".Item" ) .siblings ([Selector]) //select all siblings duplicated code
  3. Tandem

    $( "ul" ).find( "li" ).add( "p" ) //Add the selected element to the current object collection $( "ul" ).find( "li" ).addBack( "p" ) //the caller will join the current object in the collection $ ( "ul" ) .find ( "li" ), End () //return the last set of destructive operations before copying the code
  4. Traverse

    $( "ul li" ).each( function ( index,ele ) { //Process index and element object ele }) $( "ul li" ).map( function ( index,ele ) { //Process the index and element object ele //and generate a new collection return $(ele).html(); }) $( "ul li" ).length //Return the number of elements in the collection $( "ul li" ).index() //Return the index of the element in the sibling element $( "ul li" ).get([i] ) //returns the collection of native dom index corresponding to the object, the object is not native to the parameter array if $ ( "UL Li" ) .EQ (I) //returns jQuery dom object set corresponding to indexed copy the code

jQuery DOM manipulation

  1. create

    var $ img = $ ( "<img the src = '...'>" ) //create img tag elements duplicated code
  2. insert

    //Become the last child element $( "#box" ).append($img) $( "#box" ).append( "<img src='...'/>" ) $( "<img>" ).appendTo( "#box" ) //Become the first child element $( "#box" ).prepend($img) $( "#box" ).prepend( "<img src='...'/>" ) $( "<img>" ).prependTo( "#box" ) //Become the next sibling element $( "#box" ).after($img) $( "<img>" ).insertAfter( "#box" ) //Become the previous sibling element $( "#box" ).before($img) $( "<img>" ).insertbefore( "#box" ) Copy code
  3. package

    $( "#box img" ).warp( "<li>" ) //Every img is wrapped in li $( "#box img" ).warpAll( "<li>" ) //Use a li to wrap the img $ ( "#box" ) .warpInner ( "<li>" ) //li wrapped with all sub-elements $ ( "img #box" ) .unwarp (); //remove img parent element copy the code
  4. replace

    $( "#item" ).replaceWith($( "<img src='...'/>" )) $ ( "<IMG the src = '...'/>" ) .replaceAll ( "#item" ) copy the code
  5. delete

    $( "#box" ).empty() //empty all content $( "#box" ).remove() //delete the caller $( "#box" ).detach() //delete the caller //the romove () and detach () return value back to append to the specified location, you can achieve recovery //difference is that detach () event to retain, remove () does not retain copy the code
  6. clone

    $ ( "#Box" ) .clone () //return jq dom complete copy of the object copy the code

jQuery event handling

  1. Event binding

    //The event name method supports chain operation $( "#btn" ).click( function () {}) $( "#btn" ).mouseover( function () {}).mouseout( function () {}) //on method can use {} to bind multiple events $( "#btn" ) .on ( "click" , function () {}) //The one method will only be bound once and will become invalid after triggering $( "#btn" ).one( "dblclick" function () {}) //lift Event $ ( "#btn" ) .off ( "the Click" ) //do not specify the name of the event is canceled all events copy the code
  2. Event delegation

    //Many event delegation methods in jquery are deprecated. You can use on() instead of $( "#box" ).on( "click" , "li" , function () {}) //Add a click method to each li in div#box, including the newly appended li copy code
  3. Event object

    $( "#box" ).on( "click" , function ( event ) { console .log(event.type); //Event name console .log(event.pageX); //The mouse is on the horizontal axis of the document console . log(event.pageY); //The mouse is in the document coordinates console .log(event.target) //The element that triggers the event console .log(event.which) //The ascii code of the keyboard is pressed event.prevent(); //Prevent the default operation, such as href event.stopPropagation(); //Prevent event bubbling, that is, the event of the parent element will not be triggered //return false can prevent both event bubbling and default operation }) Copy code

jQuery animation

  1. Basic effect

    //Change: transparency, size-related attributes, margins //Parameters: speed: normal, fast, slow or value (milliseconds) || callback: callback method hide(); //show show(); //hide Toggle (); //switch to show and hide duplicated code
  2. slide

    //Change: vertical attributes //Parameters: speed || callback slideUp(); //expand slideDown(); //collapse slideToggle(); //expand and collapse switch copy code
  3. Fade in

    //Change: Transparency //Parameters: Speed || the callback fadeIn (); //fade . FadeOut (); //fade fadeToggle (); //state switching duplicated code
  4. Custom animation

    //Parameters: {} || speed || caback animate({ "width" : 500 , "padding" : 20 }, 3000 , function () { //callback... }) Copy code

jQuery Ajax

  1. get/post method

    //get request data is contained in url $.get(url, function () { //callback... },dataType) //If the post request does not specify data, no data will be passed //data format: {name:"Jett",password:"1234"} || name=Jett&&password=1234 $.post(url,data, function () { //callback... },dataType) Copy code
  2. ajax method

    $.ajax({ url : "..." , type : "get" , asny : true , dataType : "json" //If specified as json, it will be automatically converted to js object data :{ name : "Jett" , password : "1234" } //or "name=Jett&&password:1234" success : function () { //callback... } error : function () { //callback } }) Copy code
  3. serialize()

    $ ( "#MyForm" ) .serilaze () //specify the name of the control's content consisting return to form in a string copy the code

jQuery tool method

  1. Array

    //$.each(): Traverse arrays and class-arrays var list = [ 1 , 2 , 3 , 4 ]; $.each(, funtion ( index,item ) { console .log(index,item); }) //$.map: manipulate arrays and class-arrays, and return a new collection list = $.map(, funtion ( index,item ) { return item + 1 ; //add each element of the list by +1 }) Copy code
  2. function

    //Equivalent to native js bind() method function test () { //this -> window } .proxy $ (test, { name : "Jett" }); //this refers to the internal test function {name: "Jett"} objects copy the code
  3. judgment

    $.type(); //Return type $.isFunction(); //Is it a method? $.isWindow(); //Is it a window object $.isNumberic(); //Is it a number (not necessarily a number type , NaN return false) copy the code
  4. String

    .trim $ (); //remove the spaces on both sides of the string $ .param ({name: "Jett ", age: "22"});//Object -> String name = Jett && age = 22 duplicated code