Concept & Current Situation

  • JQuery is a fast, concise JavaScript library. The main content is to encapsulate various DOM operations. You can also think of jQuery as a library of functions and a special object. More than 90% of web sites have used jQuery, preferred for medium and large web projects. They are used less now.

What can you do for us?

  • Write Less, Do More, Do More with Less code.
  • Css manipulation, event handling, JS animation, Ajas encapsulation (AXIOS), easily extensible plug-ins

How to use it?

  1. Download the Jquery file locally and import it locally
  2. CDN:
  3. Version:
  • Version 1.0+, compatible with IE
  • Version 2.0+, some IE8 supports high execution efficiency
  • Version 3.0+, completely unsupported below IE8, provides some apis; A version without Ajax/ animation APIS is provided

Said Jquery so much of the good, is not worried about me to deceive you, come on, we first look at an example 😊

  • TAB: When we click on a TAB, the corresponding image is displayed below
// This is our HTML part and CSS part (shared below)<div id="tab">
    <ul>
      <li class="active">
        <a href="#">The car</a>
      </li>
      <li>
        <a href="#">The city landscape</a>
      </li>
      <li>
        <a href="#">Polar view</a>
      </li>
    </ul>
    <p class="show"><img src=".. /img/1.jpg" alt=""></p>
    <p><img src=".. /img/2.jpg" alt=""></p>
    <p><img src=".. /img/3.jpg" alt=""></p>
  </div>
  <style>
  /* Clear and define the format */
  * {
    padding: 0;
    margin: 0;
  }
  ul {
    list-style: none;
  }
  ul li a {
    text-decoration: none;
    color: black;
  }
  /* CSS style */
  #tab {
    width: 600px;
    margin: 20px auto;
    border: 1px solid cornflowerblue;
  }
  ul {
    width: 100%;
    overflow: hidden;
  }
  ul li {
    float: left;
    width: 33.33%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color: #cccccc;
  }
  p {
    height: 200px;
    text-align: center;
    line-height: 200px;
    background-color: #fff;
    /* Initial state, all images hidden */
    display: none;
  }
  img {
    width: 100%;
  }
  /* Image response class */
  p.show {
    display: block;
  }
  /* Click on the label's response class */
  li.active {
    background-color: cornflowerblue;
  }
</style>
Copy the code
  • The native JS implementation looks like this 🚗
    // Get all tags corresponding to the click event
    var lis = document.querySelectorAll("li");
    // Get the picture response for the click event
    var allimg = document.querySelectorAll("p");
    // Iterate over the 3 click events to get the index
    for (var i = 0; i < lis.length; i++) {
      // Create a custom attribute in the click event and assign the corresponding label to the new attribute
      lis[i].dataset.numimg = [i]
      // Construct the click event method
      lis[i].onclick = function () {
        // Before a click takes effect, iterate over three click events to delete their active class
        for (var j = 0; j < lis.length; j++) {
          lis[j].classList.remove("active");
        }
        // Add the active class to the name of the currently clicked label
        this.classList.add("active");
        // The image response subscript corresponding to the click event
        var numimg = this.dataset.numimg;
        // Images are iterated over 3 images before they respond, with the purpose of removing their show class
        for (var k = 0; k < allimg.length; k++) {
          allimg[k].classList.remove("show");
        }
        // Add the show class name to the image corresponding to the currently clicked label name
        allimg[numimg].classList.add("show"); }}Copy the code
  • The Jquery implementation looks like this ✈
// Import the local Jquery library. Here we are using version 3.5.1
 <script src="Js/jquery3.5.1. Js"></script>
  <script>
    $(function(){$("#tab ul li").click(function(){$(this).addClass("active").siblings().removeClass("active");
        $("#tab p").eq($(this).index()).addClass("active").siblings().removeClass("active");
      });
    });
  </script>
Copy the code
  • Isn’t that shocking, right, you read that right, a handful of code implements the TAB ❤

Let’s get to the point and start to understand this amazing thing 🐱🏍

Jquery core objects and core functions

$or jQuery defines global functions for us to call. The function is different depending on the parameters passed in.

  • 1. The parameter is a function: After the page is loaded, execute it. This is similar to the window.onload function.Copy the code
  • 2. The argument is a selector string: find all matching labels and encapsulate them into jQuery objects (pseudo-arrays).Copy the code
  • 3. The parameter is a DOM object, which is encapsulated as a jQuery object.Copy the code
  • 4. Create a DOM object and encapsulate it as a jQuery object.Copy the code
  • 5. When called as a function, the $function name () encapsulates the contents after $as a Jquery object.Copy the code

JQuery core object, the object returned after executing the core function

 // Pass the argument to a function
  $.each([3.4.5].function (index, item) { // go through the number group.
      console.log("Item #" + index + ":" + item);
    });
 // The argument is a selector string: find all matching labels and wrap them into jQuery objects (pseudo-arrays).
  let res = $("div");
  console.log(res[0]);
  // The argument is a DOM object that will be wrapped as a jQuery object.
  const box = document.getElementById('box');
  console.log($(box));
  // Create a DOM object and wrap it into a jQuery object.
  console.log($("<div>123</div>"));
  document.body.append($("<div>123</div>") [0])

Copy the code

The selector

:first Get the first element,:lastThe usage is similar

<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
</ul>$('li:first'); / / the result:<li>list item 1</li>
Copy the code

:oddMatch all elements with an odd index value, counting from 0, and find rows 2, 4, and 6 of the table (index values 1, 3, 5…).:evenMatches all elements whose index value is odd.

< table > < tr > < td > Lin 1 < / td > < / tr > / / index 0 < tr > < td > Lin 2 < / td > < / tr > / / index 1 < tr > < td > Lin 3 < / td > < / tr > / / index 2 $(tr: "odd") / / results: <tr><td>lin 1</td></tr> </table>Copy the code

parent>childMatches all child elements under the given parent element to match the element’s selector, and it is a child of the first selector

1 / / examples
<form>
  <label>Name:</label>
  <input name="name" />
  <fieldset>
      <label>Newsletter:</label>
      <input name="newsletter" />
 </fieldset>
</form>
<input name="none" />
$("form > input")[]-- -- -- -- -- -- -- -- -- -- -- -- -- -- attention to distinguish the left -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- $("form imput")[, ]
/*$(" ancestor descendants ") matches all descendant elements under the given ancestor element */
Copy the code

prev + nextMatches the first next element immediately following the prev selector

1 / / examples
$("label + input")
Copy the code

prev ~ siblingsMatch all siblings elements after prev

1 / / examples
$("form ~ input")
Copy the code

#idMatches the element with the specified ID

<div id="notMe"><p>id="notMe"</p></div>
<div id="myDiv">id="myDiv"</div>
$("#myDiv");
      
id="myDiv"
]
Copy the code

.classMatches elements based on the given CSS class name, a class to search for. An element can have more than one class, and as long as one matches, it can be matched.

<div class="notMe"> </div><div class="myClass myClass1">Big potatoes</div>
<span class="myClass">hernandez</span>
$(".myClass")
      
small peas
------------------------------------------------------------- // Draw inferences from examples $(".. myClass,.notMe")// Results I do not say you also know 😂 Copy the code

:not(selector)Removes all elements that match the given selector, supported:not("div a")andnot("div,a")

<input name="apple" />
<input name="flower" checked="checked" />
$("input:not(:checked)")[]
Copy the code

Eq (index) Matches an element with a given index value

<table>
  <tr><td>lin 1</td></tr>
  <tr><td>lin 2</td></tr>
  <tr><td>lin 3</td></tr>
</table>
 $("tr:eq(1)")// Result: [ Lin 2] $("tr").eq(1)
Copy the code

:gt(index)and:lt(index)Matches all elements – greater than/less than – the given index value

<table>
  <tr><td>lin 1</td></tr>
  <tr><td>lin 2</td></tr>
  <tr><td>lin 3</td></tr>
</table>
 $("gt:eq(0)")/ / the result: [< tr > < td > Lin 2 < / td > < / tr >, < tr > < td > Lin 3 < / td > < / tr >]
 $("lt:eq(2)")/ / the result: [< tr > < td > Lin 1 < / td > < / tr >, < tr > < td > Lin 2 < / td > < / tr >]
Copy the code

Manipulating CSS styles

<p> Monday </p><p>Tuesday</p>
  <p>Wednesday</p>
  <p>Thursday</p>
  <p>Friday</p>
Copy the code

Syntax: Jquery object.css ({style 1: value 1, style 2: value 2…….. })

 $("p").eq(0).css({
      height:"100px".fontSize:"20px".backgroundColor:"red"// Note that CSS style names for composite types need to be humped
    })
Copy the code

Supplement:offsetGets the relative offset of the matched element in the current viewport. The returned object contains two integer attributes, top and left, in pixels; It must be an object with top and left attributes.

// We use the day of the week as the test example, the default location is body
var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );

Hello

left: no px, no px

Copy the code

Operation effect (transition effect)

hideHide displayed elements (this method will not change anything if the selected element is hidden)

$("p").hide("slow");// Slow hides paragraphs in 600 milliseconds (fast 200 milliseconds)
Copy the code

toggleIf the element is visible, switch to hidden; If the element is hidden, switch to visible.

$("p").toggle("slow");// Slow to show or hide paragraphs in 600 milliseconds (fast 200 milliseconds)
Copy the code

slideDownandsliderUpDisplay all matched elements dynamically by height variation (increasing down/decreasing up), optionally firing a callback function when the display is complete. This animation only adjusts the height of the element, so that matched elements appear in a “sliding” manner.

$("p").slideDown("slow");// Slow to slide down hidden 

elements in 600ms (fast 200ms)

$("p").slideUp("slow");// Slow to slide up hidden

elements in 600ms (fast 200ms)

Copy the code

Stop Stops a running animation or effect

// Start animation
$("Origin of the event"Event type name (function(){$("Animation name").animate({left: '+200px'}, 5000);
});
// Stop animation when the button is clicked
$("Ended event source"Event type name (function(){$("Animation name").stop();
});
Copy the code

Operational events

Binding and unbinding

// There are two ways to bind events
 1.jQuery.eventName(function(){})
 2.jquery.on(eventname eventname,function(){}) eg: $("button").click(function(){... })Copy the code
// Unbind events
  jQuery.off("eventname");Copy the code

Event delegation

/ / HTML<button id="btn">add</button>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
 
Copy the code
 //js implements event delegate
  <script src="Js/jquery3.5.1. Js"></script>
   const btn = document.getElementById('btn');
   const ul = document.querySelector("ul")
   // Click the button to add a line of Li
   btn.onclick = function(){
      const li = document.createElement("li")
      li.innerHTML = ul.childElementCount+1;
      ul.appendChild(li);
    }
    // The event delegate uses ul to trigger the click event for Li
    ul.onclick = function(even){
      console.log(even.target.nodeName);
      if (even.target.nodeName=="LI") {
        even.target.style.backgroundColor = "brown"}}Copy the code
//Jquery implements event delegate
$("ul").on("click"."li".function(){$(this).css("backgroundColor"."brown"The $()})"button").one("click".function(){// One can only trigger once (li can only be added once)
      const li = document.createElement("li")
      li.innerHTML = ul.childElementCount+1;
      ul.appendChild(li);
    })
Copy the code

Manipulate attributes of elements

1. attr()

  • Read: attr(” Attribute name “) = Mainly used to get the attributes of the element, including custom attributes.
  • Write: attr(” Attribute name “,” attribute value “) to set the tag attribute of the element.

2. removeAttr()Deleting element attributes

3. attrandpropThe difference between:

  • This is recommended for reading and writing elements’ native and custom attributesprop

【 Note 】 Checked or Disable properties, use prop, otherwise Q1 will appear below

/ / HTML<p title="Title" index="1" data-index="2">You guess what</p>
<input type="checkbox" id="deal" >
<script src="Js/jquery3.5.1. Js"></script>Console. log($("p").attr("title")); Log ($("p").attr("data-abc")); $("p").removeattr ("index"); / / the result:<p title="Title"  data-abc="2">You guess what</p>$("#deal").click(function(){console.log($(this).prop("checked")); // true false console.log($(this).attr("checked")); / / Q1: undefined})Copy the code