jQuery Use Notes

jQuery Foundation

  1. Introduction to jQuery

  2. jQuery Advantages

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

    • Official Download Required Version

    • References from CDN servers, such as www.bootcdn.cn/jquery

      <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    • Run npm install jquery command in npm to download automatically

  4. jQuery Version

    • jQuery 2.0 and above, incompatible with IE 8
    • Versions below jQuery 2.0 are compatible with IE 8
    • jQuery Development Version: jquery.js with detailed comments to help developers learn and understand
    • Compressed version of jQuery: jquery.min.js, compressed, small and fast to load
  5. Compatibility introduction for jQuery

    <!--Use IE  Browser Conditional Comments-->
    <!--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>
    <!--ie8 And below-->
    <!--[if lte IE 8]>
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
  6. Use of jQuery

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

    $(document).ready() and window.onload function similar, but different

    • ready executes after the dom has been drawn
    • onload executes after the image and other external files have been fully loaded
  7. jQuery Dom object

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

    • $("#box"):jquery dom object, cannot use native method

    • Reciprocal conversion

      let jsBox = document.querySelector("#box");
      $(jsBox).html("Hello");// Use $(), JS DOM object -> JQ DOM object
      let jqBox=$("#box');//Gets a collection of DOM objects
      jqBox[0].innerHTML="Hello";// Using [subscript], JQ DOM object -> JS DOM object
  8. jQuery Global Object

    • jQuery, alias$
    • Functions of $
      • Parameter is js dom object, which is converted to jquery dom object
      • Parameter is selector, get jquery dom object
      • Parameters are labels beginning with <to create elements that can be added to the page using appendTo

jQuery Selector

  1. Basic selector

    $("#Box') // id selector Select label with id box
    $(".item") // class selector selects a label whose class is item
    $("li") // tag name selector selects all li Tags
    $("*") // gloal selector selects all tags
    $("li.item") // combo selector selects the li tag with clss as item
    $("li,p") // multi selector selects all li and p Tags
  2. Hierarchical selector

    $("ul li") // Select li from ul descendant elements
    $("ul>li") // Select li in ul child element
    $("#item+li") // Select a sibling element after #item 
    $("#item~li") // Select all sibling elements after #item
  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)") // Select the i I in li, starting at 0
    $("ul li:lt(i)") // Select li less than i, starting at 0
    $("ul li:gt(i)") // Select li greater than i, starting at 0
    $("ul li:odd") // Select elements in odd order, starting at 0
    $("ul li:even") // Select elements in even order, starting at 0
    $("ul li:not(.item)") // Select an element in li where class is not an item
    $(":header") // Select All Title Labels
    $(":focus") // Select the element to focus on
    $(":target") // Select the anchor element that the url points to, which can be either a label or an id
  4. Content Chooser

    $("li:contains(str)") // Select the li tag that contains the str internally
    $("li:has(.item)") // Select the li tag that contains elements whose class is a descendant of the item
    $("ul li:empty") // Select li without content, innerHTML.length = 0
    $("ul li:parent") // Select li, innHTML.length with content (text or child elements)!= 0
  5. Visibility selector

    $(":visible") // Select Visible Elements
    $(":hidden") // Select invisible elements
  6. attribute selectors

    $("img[alt]") // Select img tag with alt attribute
    $("img[alt='str']") // Select img tag with ALT ='str'
    $("img[alt!='str']") // Select img tag with alt!='str'
    $("img[alt^='s']") // Select img tag with alt starting with s
    $("img[alt$='r']") // Select img tag with alt ending in r
    $("img[alt][title]") // Select img tags with alt and title Attributes
  7. Child Selector

    // -child Sorts all sibling elements, starting with 1
    $("li:first-child") // Select the li tag that is li and is the first of all sibling elements
    $("li:last-child") // Select the li tag that is li and is the last of all sibling elements
    $("li:nth-child(i)") // Choose the li tag that is li and ranks third in all sibling elements
    $("li:nth-last-child(i)") // Select li and rank in the bottom i I of all sibling elements
    $("li:only-child") // Select the li tag without the sibling element
    // -of-type Sorts the specified label elements, starting with 1
    $("li:first-of-type") // Choose the li tag that is li and ranks first among all siblings
    $("li:last-of-type") // Choose the li tag that is li and ranks last among all siblings
    $("li:nth-of-type(i)") // Choose the li tag that is li and ranks third among all brothers
    $("li:nth-last-of-type(i)") // Choose the label li which is the last ith among all brothers li
    $("li:only-of-type") // Selection can have sibling elements, but only one li tag with the tag element
  8. Form Selector

    // Form Control Selector
    $(":input") //Select all form controls input/select/textarea/button...
    $(":text") // Select Text Box
    $(":password") // Select Password Box
    $(":radio") //Select Radio Button
    $(":checkbox") // Select Multiple Selection Button
    $(":file") //Select Text Fields
    $(":submit") // Select input (type=submit), button (type or type=submit is not specified)
    $(":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, checkbox selected elements
    $(":selected") // Select the element selected in the drop-down list

jQuery Properties and Styles

  1. Property Operation

    attr(attrName[,attrValue]) // Operate on all properties, including custom properties
    prop(attrName[,attrValue]) //Operate canonical properties
    removeAttr((attrName) // Delete Properties
    removeProp((attrName) // Remove attributes added through prop()
    attr("class",value) // Property Settings
    hasClass(className) // Determine if there is a corresponding class
    addClass(className) // Add class
    removeClass(className) // Remove class
    toggleClass(className) // Remove the class if it exists, add it 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 attribute
        $("#Img-item'). attr ('src'); //Get SRC
        $("#Img-item').prop ('src'); //Get SRC
        $("#Img-item').attr('testAttr'); //Get testAttr
        $("#Img-item').prop ('testAttr'); //Unable to get non-conforming properties, undefined
        // set a property
        $("#Img-item').attr('src','...'); //Set SRC
        $("#Img-item').prop ('src','...'); //Set SRC
  2. Style operation

    // css
    css("background-color","#ccc') //Set or get css properties
    css({"width":"400px","height":"200px"}) // Setting multiple css properties at once
    // position
    offset() // Gets or sets the coordinates of the element in the document (top,left)
    position() // The coordinates of the element in the positioned ancestor element (top,left)
    srollTop() // Gets or sets the Y scrollbar position
    scrollLeft() // Gets or sets the X scrollbar position
    // size
    width(),height() // Set or Get Content Size
    innerWidth(),innerHeight() // Set or get the sum of content size and padding
    outerWidth(),outHeight() //Set or get box size
  3. Text Operation

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

jQuery Filtering

  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 to the i jq dom object
    $("ul li").not(".itme") // Returns a collection after excluding objects that satisfy class = item
    $("ul li").filter(".item") // Returns a collection of objects that meet the class = item condition
    $("ul li").slice(a[,b]) // Returns a to the last element or a to b (left closed right open) collection of objects
    $("ul li").has('.item') // Returns a collection of objects with child elements of class item
  2. lookup

    $("ul").children([selector]) // Select the child elements that meet the criteria
    $("ul").find("li") // Select descendant elements that meet the criteria
    $("ul").parent([selector]) // Select the parent element that meets the criteria
    $("ul").parents([selector]) // Select ancestor elements that meet the criteria
    $("ul").parentsUntil([selector]) // Select all ancestor elements until selector (excluding selector)
    $("ul").offsetParent() // Select the first positioned ancestor element, or the html tag if none
    $(".item").next([selector]) // Select the next sibling element that meets the criteria
    $(".item").nextAll([selector]) // Select all sibling elements that meet the criteria
    $(".item").nextUntil([selector]) // Select all subsequent sibling elements until selector (excluding selector)
    $(".item").prev([selector]) // Select the first sibling element that meets the criteria
    $(".item").prevAll([selector]) //  Select all the first sibling elements that meet the criteria
    $(".item").prevUntil([selector]) // Select all previous sibling elements until selector (excluding selector)
    $(".item").siblings([selector]) // Select all sibling elements
  3. Series connection

    $("ul").find("li").add("p") // Add selected elements to the current object collection
    $("ul").find("li").addBack("p") // Add caller to current object collection
    $("ul").find("li"),end() // Returns the collection before the last destructive operation
  4. ergodic

    $("ul li").each(function(index,ele){
        // Processing sequence number index and element object ele 
    $("ul li").map(function(index,ele){
        // Processing sequence number index and element object ele
        // And generate a new set
        return $(ele).html();
    $("ul li").length // Returns the number of elements in a collection
    $("ul li").index() // Returns the index of an element in a sibling element
    $("ul li").get([i]) // Returns the native dom object of the corresponding index in the collection, or an array of native objects without parameters
    $("ul li").eq(i) // Returns the jquery dom object for the corresponding index in the collection

jQuery DOM Operation

  1. Establish

    var $img = $("<img src='...'>") // Create img tag element
  2. insert

    // Become the last child element
    $("#box").append("<img src='...' />")
    // Become the first of the child elements
    $("#box").prepend("<img src='...' />")
    // Become the next sibling element
    // Become the previous sibling element
  3. package

    $("#box img"). warp ("<li>")//Each img is wrapped in Li
     $("#box img"). warpAll ("<li>")//Wrap img with a li 
    $("#box"). warpInner ("<li>")//Wrap all child elements in Li
     $("#box img").unwarp(); //Remove the parent element of img
  4. replace

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

    $("#box").empty()//Empty everything
     $("#box").remove()//delete caller
     $("#box").detach()//Delete caller
     //append the return values of romove() and detach() back to the specified location for recovery
     //The difference is detach() retains events, remove() does not
  6. Clone

    $("#box").clone()//Return a fully copied jq dom object

jQuery event handling

  1. Event Binding

    // Event name method supports chain operation
    // The on method can bind multiple events with {}
    // one method only binds once and fails after triggering
    // Release Event
    $("#BTN').off ('click')//Release all events without specifying an event name
  2. event delegation

    // Many event delegation methods in jquery have been discarded and can be replaced with on()
    // Add click methods to every li in div#box, including the li into which the new append enters
  3. Event Object

        console.log(event.type); // Event Name
     console.log(event.pageX); // Mouse in Document X-coordinates
        console.log(event.pageY); // Mouse in Document Crowd Coordinates
        console.log(event.target) // The element that triggers the event
        console.log(event.which) // Press the ascii code of the keyboard
        event.prevent(); // Prevent default actions such as href for a tag
        event.stopPropagation(); // Prevent event bubbles, that is, events that do not trigger parent elements
        // return false prevents both event bubbles and default operations

jQuery Animation

  1. Basic effects

    // Changes: transparency, size-dependent attributes, margins
    // Parameter: speed:normal, fast, slow or numeric (milliseconds)|| callback: Callback method
    hide(); // display
    show(); // hide
    toggle(); // Show and Hide Toggle
  2. Slide

    // Change: Attributes in the vertical direction
    // Parameter: speed || callback
    slideUp(); // Open
    slideDown(); // Receive
    slideToggle(); // Expand and and close switch
  3. Fade in and out

    // Change: Transparency
    // Parameter: speed || callback
    fadeIn(); // Fade in
    fadeOut(); // Fade out
    fadeToggle(); // State Switch
  4. Custom Animation

    // Parameters: {} || speed || caback
        // callback...

jQuery Ajax

  1. get/post method

    // get request data contained in url
        // callback...
    // The post request does not specify data and does not pass data
    // data format: {name:'Jett', password:'1234'} | name=Jett &&password=1234
        // callback...
  2. ajax method

        dataType:"json" // Specified as json, automatically converted to js object
        data:{name:"Jett",password:"1234"} // Or "name=Jett &&password:1234"
            // callback...
            // callback
  3. serialize()

    // Returns a string of control contents specified name in the form

jQuery Tool Method

  1. array

    // $.each(): traverse arrays and class arrays
    var list = [1,2,3,4];
    // $.map: array of operations and arrays of classes, returning a new set
    list = $.map(,funtion(index,item){
        return item + 1; // list each element + 1
  2. function

    // Equivalent to native js bind() method
    function test(){
        // this -> window
    $.proxy(test,{name:"Jett"}); //Point this inside the test function to the {name:'Jett'} object
  3. judge

    $.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 returns false)
  4. Character string

    $.trim(); // Remove whitespace on both sides of a string
    $.param({name:"Jett",age:"22"}); // Object->String name=Jett &&age=22

Keywords: Javascript JQuery IE Attribute

Added by Cyberspace on Sun, 23 Feb 2020 04:44:42 +0200