The introduction of the jquery

  • JQuery is a JavaScript library that contains a large number of properties and methods for project development. JQuery greatly simplifies JavaScript programming.
  • The version of jQuery
    • The first generation version of 1.xx.xx, such as 1.11.3, features compatibility with all browsers (including IE6 to IE8), and before vue/ React/Angular frameworks (data-driven), projects were based on DOM operations. Basically the project is jQuery.
    • The 2nd generation version 2.xx.xx, which has abandoned the compatibility processing of the lower version browser, caters to some mobile development processing (also created a more mobile library Zepto than JQ, so the 2nd generation version is a weak point).
    • The third generation version, 3.xx.xx, did not deal with the compatibility of older browsers, but by this time the project entered the era of framework development, and the idea of traditional DOM manipulation was gradually abandoned, so JQ had fallen into disuse.

The jQuery library contains the following features:

  1. HTML element selection

  2. HTML element manipulation

  3. CSS operation

  4. HTML event function

  5. JavaScript effects and animations

  6. HTML DOM traversal and modification

  7. AJAX

  8. Utilities

Commonly used jQuery selector

  • Get the DOM element that you want to manipulate. The result is (JQ object => array of classes). Only JQ objects can call a DOM manipulation method provided by JQ.

Methods to manipulate the DOM

Filtering, traversal methodschildren/find/filter/eq(get)/prevAll/next/nextAll/siblings/index...

Get the DOM element

  • Eq (index) returns the element with the specified index of the selected element, and the return value is a JQ object (init(1)). The JQ method can still be called

    let $div = $('div')
    $div.eq(0).css('color'.'red') // Set the font color to red for the first div
    Copy the code
  • Get (index) returns the indexed element of the selected object, and the return value is a native DOM object that can use properties and methods provided by native browsers.

    $("div").click(function() {
       x = $("div").get(0);
       $("div").text(x.nodeName + ":" + x.innerHTML);
    });
    Copy the code
  • The children(select) method returns all direct children of the selected element, and selcet is typically a string value containing a selector expression for the matching element.

    $("ul").children()// Return all the children of ul, the return value is JQ object
    Copy the code
  • Find (select) // Returns all selected select elements. The return value is also a JQ object

    $("p").find("span").css('color'.'red');// Return all span tags in the P tag and set the font color to red
    Copy the code

Traversal methods

  • prevAll('select'), returns all elements of the select class, but only under the same parent.
  • prev('select')Select the last element of the same level, must be the same parent of the element.
    <ul class="level-1">
        <li class="item-i">I</li>
        <li class="item-ii">II
            <ul class="level-2">
                <li class="item-a">A</li>
                <li class="item-b">B
                    <ul class="level-3">
                        <li class="item-1">1</li>
                        <li class="item-2">2</li>
                        <li class="item-3">3</li>
                    </ul>
                </li>
                <li class="item-c">C</li>
            </ul>
        </li>
        <li class="item-iii">III</li>
        </ul>
    
        console.log($('.item-3').prevAll());// li.item-1 li.item-2
        console.log($('.item-3').prev());// li.item-2
    Copy the code
  • next('select')Returns the next element of the same level, which must be under the same parent element.
  • nextAll('select'), returns all elements of the same parent element.
    console.log($('.item-1').next())// Return the same parent as the next element of type item-1
    console.log($('.item-1').nextAll())// li.item-2 li.item-3
    Copy the code
  • siblings('select')Gets all siblings of the selected element under the same parent element.
    console.log($('.item-2').siblings())// li.item-1 li.item-3
    Copy the code
  • index('select')Gets the index position of the selected element under the same parent element
    console.log($('.item-3').index()) / / 2
    Copy the code

Operating stylecss/addClass/removeClass/toggleClass/hasClass/innerWidth...

  • css()Use to return the value of the selected style or to set one or more styles
    $('item-2').css('color') // Returns the color style for the element of class item-2
    
    $('item-2').css(background: 'red')// Set the background color of the element named item-2 to red
    
    // Set the syntax for multiple styles
    $('item-2').css({color:'red'.background:'black'})
    Copy the code
  • addClass('select')Adds the class name to the selected element
  • removeClass('select')Removes the class name for the selected element
    $('item-2').addClass('lis'The $()'item-2').removeClass('lis')
    Copy the code
  • toggleClass(class,switch)To add or remove a class name to the selected element, class is mandatory, and switch is optional. Switch specifies whether to add or remove a value of true or false.
    $('item-2').toggleclass ('lis') // Add or remove the class name to see if the selected element has an LIS class nameCopy the code
  • hasClass('select'), returns true or false if the select class name exists for the selected element
    console.log($('li').hasClass('lis')) // true
    Copy the code
  • innerWidth()Returns the internal width of the selected element, including the padding and excluding the border and margin.
  • outerWidth()Returns the outer width of the selected element, including padding and border, or if margin is requiredouterWidth(true)

Operating contenthtml/text/val/append/appendTo/insertAfter/attr...

  • html()Returns or sets the contents of the selected element. If the method does not write any arguments, it returns the content.html(content)) is to set parameters. Content contains HTML tags.
  • text()Sets or returns the text content of the selected element.
  • val()Returns or sets the value of the selected element, typically used in an input form.
  • append(content)Inserts content, which can be an HTML tag, at the very back of the interior of the selected element.
  • appendTo(), inserts content at the end of the selected element, just like append, but written differently.
  • insertAfter()Inserts content after the selected element.
    $('content').appendTo('selector')// Content is the content to add, and selector is the selector of the selected element.
    $('content').insertAfter('selector') // The syntax is shown above
    Copy the code
  • attr()Sets or returns the attribute value of the selected element.

Control the animationanimate/finish/fadeIn/fadeOut/hidde/show/slideDown/slideUp...

  • animate()For creating animations, only numeric values can create animations (e.g. “margin:30px”). String values cannot create animations (such as “background-color:red”).
    $(selector).animate({params},speed,callback)
    // Params required, which is the CSS property that forms the animation, speed is optional, which specifies the animation duration (slow, fast, or milliseconds), and callback is optional, which is the function to execute after the animation is executed.
    $('div').animate({
        width:'100px'.height:'+=120px'
    })
    Copy the code
  • finish()Method stops the currently running animation, removes all queued animations, and completes all animations for the selected element.
  • fadeIn()Use the fade effect to show the selected element if it is hidden.
  • fadeOut()Use fade to hide the selected element.
  • $(selector).hide(speed,callback), hides the selected element, speed and callback are optional.
  • slideDown()If the selected element is hidden, the animation below shows the selected element.
  • slideUp()The pull up form hides the selected element

Action event bindingon/off/bind/unbind/delgate/one

  • off()Typically used to remove event handlers added through the on() method.
  • one()The event is removed after it fires once.
  • bind()The selected element adds one or more event handlers and specifies the functions to run when the event occurs.
  • unbind()Removes the event handler for the selected element.
  • delegate()Method adds one or more event handlers to the specified element (a child of the selected element) and specifies the functions to run when those events occur.

Utility class methodseach/ajax...

  • $(selector).each(function(index,element)), loop through each LI and execute the function

ajax

  • Ajax is used by the browser to communicate with the server without refreshing the entire page. Instead of returning the entire page, the server will return a small amount of data, updating a few nodes through the JavaScript DOM. During the data transmission can be used in XML, JSON and other formats, Ajax was first used in Google search tips. There are many ways to communicate with the server without refreshing the entire page, such as Flash, Java applets, iframe, etc., but Ajax is by far the most common.

  • XML, HTML, TEXT, JSON and JSONP are common formats used for data transmission between the browser and server. Currently, JSON is very popular because it occupies less storage and is a JavaScript native format.

  • $. Ajax ({name: val, name: val… }), where the optional fields of name are as follows

    • Url: link address It is a string of characters
    • Data: The format of the parameter to be sent to the server is key-value pair
    • Type: indicates the form of the requested datagetandpost
    • Timeout: request timeout, in milliseconds
    • Cache: Indicates whether to cache the result of a request. Val is a Boolean
    • ContentType: Content format, default"application/x-www/form-urlencoded"
    • DataType: the dataType of the server response. Val is a string formatjson,jsonp, etc.
    • Success: function to be called back by the server after a successful request.
    • Error: callback function of the server when a request fails
    • Complete: A function called after the request is complete, executed whether the request succeeds or fails, and executed after sucess and error
    • Async: whether to process asynchronously. Val is a Boolean type. The default value is BooleantrueIf it isfalse, js will wait for the requesting function to complete before executing the following code.
    • Username: indicates the username carried in the access authentication request. The value is a string of val
    • Password: Returns the password carried in the authentication request in the format of val
    // The original call method
    $.ajax({
        url: '/greet'.data: {name: 'hello'},
        type: 'POST'.dataType: 'json'.success: function(data){
            data: jQuery.parseJSON(data) //dataType specifies that the returned data is of json type, so no further deserialization is required}})// Simplify
    $.post(
        '/greet',
        {naeme: 'hello'},
        function(data){... },'json'
    )
    
    $.get(
          '/greet',
        {naeme: 'hello'},
        function(data){... },'json'
    )
    
    /** $getJSON, this method uses get to perform ajax requests and load JSON data from the server in the form of $.getjson (URL, data, func). $.load(), which inserts the data loaded by the server directly into the specified DOM. If data exists, the request is sent using POST, and if data does not exist, the request is sent using GET. * * /
    <div id="ret"></div>
        $('#ret').load(
        "/greet",
        {name: 'Brad'})Copy the code

Ajax basics

  • Ajax four steps

        let xhr = new XMLHttpRequest() // Create an xmlHttpRequest object also called creating an Ajax instance.
        xhr.open('GET',url? xxx=xxx,false)// Open the URL (set to send request information), the third parameter is asynchronous, the default is true, the question mark pass parameter
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200) {let result = xhr.responseText
                 }
            }// listen for the AJAX state and get the server response when the status code is 0,1,2,3,4
       xhr.send()  // Send a request, send is the body of the request, set the request body can achieve the information to the server. (reference)
    Copy the code
  • Xhr.setrequestheader () is passed to the server by setting the request header.

  • Ajax’s five status codes

Status code describe
0 (uninitialized) The send() method has not been called
1 (Load) Send () has been called and the request is being sent
2 (Load completed) After send() is executed, all response messages are received
3 (Interaction) Parsing the response content
4 (Done) The response content is parsed and ready for the client to call

XML

  • XMML is an extensible markup language designed to transfer or store data.

Common JQ events

The Event function Bind function to
$(document).ready(function===$(function(){}) Execute the function when the document is finished loading
$(select).click(function)===$(select).on('click',function(){}) The function starts when the selected element is clicked
$(select).dbclick(function) Fires when the selected element is double-click
$(selectselect).focus(function) Fires when the selected element gets focus
$(select).mouseover(function(){}) Fires when the mouse moves over the selected element