1. Introduction of jquery

1.1 What is jquery

JQuery is a JavaScript function library.

To put it bluntly, jQuery encapsulates JS and is equivalent to a JS utility class.

JQuery has everything that js has, but it also has a lot of plugins that simplify the code we write.

If JS is the subancient beast of digimon, jQuery is the fighting Tyrannosaur that has evolved and gotten stronger.

1.2 Why jquery

  • It is compatible with all browsers on the market
  • Free and open source, small capacity
  • There are many useful plug-ins
  • Simplify code. No need to write a bunch of stinky long code inside script tags.

For example, get element node:

Javascript code:var div = document.getElementById("div"); JQuery code:var div = $("div");
Copy the code

2. Use

Official website download address:

https://jquery.com/download/
Copy the code

Click on it and you’ll see a lot of messy code. This is the source code for JQuery, copy and paste it as jquery.js.

Then introduce it into your project.

Introduce syntactic formats:

<script type="text/javascript" SRC ="jquery.js file path ">Copy the code

Such as:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A Rebus</title>
    <script src="jquery.js"></script>
</head>
<body>
   
</body>
</html>
Copy the code

We can also use the online import of jquery.js:

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> .... There are many onlineCopy the code

3. The selector

JQuery’s selectors can manipulate all elements in HTML, which is essentially DOM manipulation.

Get JQuery element nodes starting with $.

3.1 Element selectors

Syntax format:

$(" element ")Copy the code

For example, get the div element node

$("div")
Copy the code

3.2 ID selector

Syntax format:

$("#id")
Copy the code

Such as:

<body>
    <p id="p1">Take an examination of grind immediately, wish everybody all go ashore!</p>
    <script>
        var p1 = $("#p1");
    </script>
</body>
Copy the code

3.3 Class selector

Syntax format:

$(".class")
Copy the code

Such as:

<body>
    <p class="p2">Take an examination of grind immediately, wish everybody all go ashore!</p>
    <script>
        var p2 = $(".p2");
    </script>
</body>
Copy the code

3.4 Combinatorial selectors

Combinatorial selectors are comma-separated elements that combine ids, classes, tag names, and so on.

Syntax format:

$("id,class, tag name ")Copy the code

For example, select all div elements with id p1 and class P2.

$("#p1,.p2,div")
Copy the code

3.5 Form pickers

Form element selectors mainly refer to the selectors of text boxes, checkboxes, checkboxes and other elements.

  1. Select all text boxes
$(":text")
Copy the code
  1. Select all the password boxes
$(":password")
Copy the code
  1. Select all the checkboxes
$(":radio")
Copy the code
  1. Select all the check boxes
$(":checkbox")
Copy the code

4. DOM manipulation

We learned from DOM trees that in order to change the values of attribute nodes and text nodes, we must first find their element nodes.

So once we get the element node we can manipulate the attribute node and the text information underneath the element node.

4.1 Obtaining/Setting Content

  1. Text () – Sets or returns the text content of the selected element

Such as:

<body>
    <p id="p1">Take an examination of grind immediately, wish everybody all go ashore!</p>
    <script>
        var info = $("#p1").text();
        document.write("<h1>"+info+"</h1>");
    </script>
</body>
Copy the code

Running results:

  1. HTML () – Sets or returns the content of the selected element (including HTML elements)

Such as:

<body>
    <p id="p1">Class, the final exam is coming.<b>Have a good day! Before! Before!</b></p>
    <script>
        var info = $("#p1").html();
        document.write("<h1 style='color:red'>" + info + "</h1>");
    </script>
</body>
Copy the code

Running results:

  1. Val () – Sets or returns the value of the form field

Such as:

<body>
    <input type="text" style="width: 210px;" value='There's nothing about you but your good looks.'>
    <script>
        var info = $("input").val();
        document.write("<h1 style='color:red'>"+info+"</h1>");
    </script>
</body>
Copy the code

Running results:

4.2 Obtaining/Setting Properties

The attr() and prop() methods are used to get and set properties.

Syntax format:

Attr (" Attribute name "," attribute value "); JQuery element node. Prop (" Attribute name "," attribute value ");Copy the code

Such as:

<body>
    <p id="p1">I'm a cute, sexy P-factor</p>
    <a href="http://www.baidu.com">I'm a sentimental hyperlink</a><br>
    <script>
        // Get attributes
       var id = $("#p1").attr("id");
       document.write("P tag id attribute value:"+id+"<br>");
       document.write(The original href value of the a tag:+ $("a").attr("href") +"<br>");
       // Modify attributes
       $("a").attr("href"."https://www.bilibili.com/");
       document.write("Href value after the A tag:"+ $("a").attr("href") +"<br>");
    </script>
</body>
Copy the code

Running results:

4.3 Adding Elements

You can use JQuery to add new elements to your HTML code.

  1. Append () – Inserts content at the end of the element.

Such as:

<body>
    <p id="p1">Before my bed a pool of night</p>
    <script>
      $("#p1").append("I think it's frost on the ground.")
    </script>
</body>

Copy the code

Running results:

  1. Prepend () – Inserts content at the beginning of the element

Such as:

<body>
    <p id="p1">Raised a pool of gull herons.</p></p>
    <script>
      $("#p1").prepend("Make haste, make haste,")
    </script>
</body>
Copy the code

Running results:

  1. Before () – Inserts content before the element

Such as:

<body>
    <h1>He who wants to speak sheds tears first.</h1>
    <script>
      $("h1").before("Things are not everything,")
    </script>
</body>
Copy the code

Running results:

  1. After () – Inserts content after the element

Such as:

<body>
    <h1>"Plum Blossom · Red lotus fragrance remnant jade mat autumn" clip</h1>
    <script>
        var txt1 = "

A lovesickness,

"
; var txt2 = $("<p></p>").text("Two sorrows."); var txt3 = $("<p></p>").text("There is no remedy for this,"); var txt4 =

frown,

; var txt5 = "

is on my mind.

"
; $("h1").after(txt1, txt2, txt3, txt4, txt5);
</script> </body> Copy the code

Running results:

4.4 Deleting Elements

With jQuery, you can easily remove existing HTML elements.

  1. Remove () – Removes the selected element (including child elements)

Such as:

<body>
    <h1>The contents of the following divs have been deleted</h1>
    <div>
        <p>I'm a child of div</p>
    </div>
    <script>
        $("div").remove();
    </script>
</body>
Copy the code

Running results:

  1. Empty () – Removes child elements from the selected element

Such as:

<body>
    <h1>The second son in div has been removed</h1>
    <div>
        <p id="p1">I'm Div's oldest son</p>
        <p id="p2">I am div's second son</p>
    </div>
    <script>
        $("#p2").empty();
    </script>
</body>

Copy the code

Running results:

4.5 Show/Hide Elements

  1. The show() method displays elements

Such as:

<body>
    <h1>The hidden div comes to the surface</h1>
    <div style="display: none;">
        <p id="p1">I'm Div's oldest son</p>
        <p id="p2">I am div's second son</p>
    </div>
    <script>
        $("div").show();
    </script>
</body>
Copy the code

Running results:

  1. The hide() method hides elements

Such as:

<body>
    <h1>The div element is hidden</h1>
    <div style="display: none;">
        <p id="p1">I'm Div's oldest son</p>
        <p id="p2">I am div's second son</p>
    </div>
    <script>
        $("div").hide();
    </script>
</body>
Copy the code

Running results:

4.6 Operating the Class Class

You can manipulate the value of the classs attribute of an element using JQuery.

  1. AddClass () – Adds one or more classes to the selected element

Such as:

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>A Rebus</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <style>
        .pp {
            color: palevioletred;
            font-size: 20px;
        }
    </style>
</head>

<body>
    <p>I'm the prettiest guy on the street!</p>
    <script>
        $("p").addClass("pp");
    </script>
</body>

</html>
Copy the code

Running results:

  1. RemoveClass () – Removes one or more classes from the selected element

Such as:

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>A Rebus</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <style>
        .p1 { color: palevioletred; }
        .p2 { font-size: 20px; }
        .p3 { font-weight: bold; }
    </style>
</head>

<body>
    <p class="p1 p2 p3">You, a look at me, a look at the clouds. I think, when you look at me far away, you look at the clouds very close.</p>
    <script>
        $("p").removeClass("p1");
    </script>
</body>

</html>
Copy the code

Running results:

4.7 Setting CSS Properties

  1. Set a single CSS property

Such as:

<body>
    <p>Facing the sea, with spring blossoms.</p>
    <script>
        $("p").css("color"."red");
    </script>
</body>
Copy the code

Running results:

  1. Set multiple CSS properties

To set multiple CSS properties, use curly braces and key-value pairs.

Such as:

<body>
    <p>I left quietly, as quietly as I came.</p>
    <script>
        $("p").css({"color":"red"."font-size":"30px"});
    </script>
</body>
Copy the code

Running results:

4.8 Go through the number group

The each method iterates through the array, calling the function once for each element.

Syntax Format 1:

$. Each (array to iterate over, function(index,element) {handler}) index: the index of the array element: the element in the arrayCopy the code

Syntax Format 2:

Each (function(index, element) {handler}) element: an element in an arrayCopy the code

Example 1:

<script>
  var animals =["cat"."pig"."dog"];
  $.each(animals,function (index,element) {
      document.write("Subscript:+index+"Element:"+element+"<br>");
  })
</script>
Copy the code

Running results:

Example 2:

<body>
    <span>Newton</span>
    <span>Einstein</span>
    <span>tesla</span>
    <script>
      $("span").each(function(index,element) {
          document.write(index+""+element.text()+ "</br>");
      })
    </script>
</body>
Copy the code

Running results:

5. Events

Events are designed for user interaction. Events are triggered when the user does something, such as pressing a keyboard or clicking a button, to execute the code in the specified function.

Note: The name of the listener event in JQuery is the content after removing on from the JS event.

5.1 DOM Events commonly used by JQuery

The event describe
click Click element events
mouseenter Mouse over an element
mouseleave Mouse away from an element
hover Hover over an element
keydown Press the keyboard
submit Submit the form
change The value of the text box changed
focus Get focus
blur Lose focus

There are two ways to handle events in JQuery: listening events and binding events.

5.2 Listening Events

Syntax format:

$(selector). The name of the event to listen on (the function that handles the event);Copy the code

Example 1: Listen for click events

<body>
    <p>You click on me, I'll make a box for you</p>
    <script>
        $("p").click(function () {
            alert("You're a real smart cookie.");
        });
    </script>
</body>
Copy the code

Running results:

Example 2: Listen for mouse hover events

<body>
    <p>You hover your mouse over me and I have a surprise for you</p>
    <script>
        $("p").hover(function () {
            alert("You are so obedient!!");
        });
    </script>
</body>
Copy the code

Running results:

5.3 On Binding Events

The on() method adds an event handler to the selected element.

Syntax format:

. On ("event",data,function) event: One or more events separated by Spaces. Data: Optional. Parameter to be passed in JSON format. Function: optional. Defines the function to execute when an event occurs.Copy the code

Example 1: Bind click events

<body>
    <p>Don't you dare point at me!</p>
    <script>
       $("p").on("click".function () {
           alert("Oh, you are!")})</script>
</body>
Copy the code

Running results:

Example 2: Bind mouse hover events

<body>
    <p>Hit Output name</p>
    <h1></h1>
    <script>
       $("p").on("click", {name:"Porgy."},function (event) {$("h1").html(event.data.name);
       })
    </script>
</body>
Copy the code

Running results:

6. Execute the method after DOM is loaded

We know that executing code in the script tag when the DOM tree is not fully loaded will result in an error, so we need a DOM loaded entry to execute the method.

A:

$(document).ready(function(){executor});Copy the code

Method 2:

$(function(){executor});Copy the code

Three:

Function ($) {function($)});Copy the code

We usually use method two because of its simple syntax.

7. JQuery example: Caroute diagram

A carousel is a picture that is switched at regular intervals.

So we only need three steps to make a rote map:

  • The page initializes a photo
  • Call the interval function setInterval and change the value of the SRC attribute for the image
  • When the last photo is displayed, it is replaced with the first photo

This time we’ll add a little bit of functionality:

  • Add button icon, click button to switch pictures
  • The button is selected along with the image switch

The source code:

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>A Rebus</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <style>
        #carouseMain {
            width: 400px;
            margin: auto;
        }
        #btnDiv {
            width: 100px;
            border-radius: 40px;
            background-color: rgb(119.117.117);
            margin: auto;
            margin-top: -35px;
            opacity: 0.7;
        }
    </style>
</head>

<body>

    <body>
        <div id="carouseMain">
            <! 1. Initialize a photo -->
            <img src="image/1.jpg" width="400px" height="200px" id="img1" />
        </div>
        <! - button - >
        <div id="btnDiv">
            <input type="radio" name="carouseBtn" id="btn1" value="1" checked>
            <input type="radio" name="carouseBtn" id="btn2" value="2">
            <input type="radio" name="carouseBtn" id="btn3" value="3">
            <input type="radio" name="carouseBtn" id="btn4" value="4">
        </div>

        <script>
            // 2. Call the image modification method every once in a while
            setInterval("changeImg()".2000);

            var i = 0
            function changeImg() {
                i++;
                // 3
                $("#img1").attr("src"."image/" + i + ".jpg");
                // 4. The Settings button is selected
                $("#btn" + i).prop("checked".true);
                // When it is the last image, replace it with the first image
                i = (i== 4)?0 : i;

            }
            // Click button event
            $(':radio').change(function () {
                // The value of the selected button
                var value = this.value;
                $("#img1").attr("src"."image/" + value + ".jpg");
                $("#btn" + value).prop("checked".true);
                i = value;
                i = (i == 4)?0 : i;
            });
        </script>
    </body>
</body>
</html>
Copy the code

Running results: