JQuery notes collation tutorial (common API and foundation)


This article is a note I made in learning dark horse course. I often take it out when I forget the knowledge points. It basically includes the knowledge you need to know about jQuery

1. Introduction to jquery

1. Overview

Warehouse: you can put a lot of things in this warehouse. Just go to the warehouse to find something.

JavaScript Library: namely library, is a specific collection (Methods and functions) encapsulated. To understand the library from the perspective of encapsulating a large number of functions, it is in this library that many pre-defined functions are encapsulated, such as animation, hide, show, and getting elements.

Simple understanding: it is a JS file, which encapsulates our native JS code and stores it. In this way, we can use these packaged functions quickly and efficiently.

For example, jQuery is for quick and convenient operation of DOM, which is basically functions (Methods).

Common JavaScript libraries: jQuery, prototype, YUI, Dojo, ext JS, mobile zepto. These libraries are the encapsulation of native JavaScript, and all of them are implemented with JavaScript. We mainly study jQuery.


  • Lightweight. The core file is only tens of KB, which will not affect the page loading speed
  • Cross browser compatibility. Basically compatible with the current mainstream browser
  • Chain programming, implicit iteration
  • Support for events, styles and animations greatly simplifies DOM operation
  • Support plug-in extension development. There are rich third-party plug-ins, such as tree menu, date control, carousel chart, etc
  • Free and open source

2. Basic use



Download of each version:https://code.jquery.com/

Development (syntax preserved) and compression

JQuery notes collation tutorial (common API and foundation)

1. Entry function of jquery

    ... // here is the entry to complete loading the dom of the page
    ... // here is the entry to complete loading DOM on page 1
  1. After the DOM structure is rendered, the internal code can be executed. Without waiting for all external resources to be loaded, jQuery helps us complete the encapsulation.
  2. It is equivalent to domcontentloaded in native JS.
  3. Different from the load event in native JS, the internal code is executed after the page document, external JS file, CSS file and image are loaded.

2. Top level object of jquery$

  1. $is another name for jQuery. In code, you can use jQuery instead of $, but for convenience, you usually use $.
  2. $is the top-level object of jQuery, which is equivalent to window in native JavaScript. You can call the method of iquer by wrapping the element as a query object with $.

3. JQuery object and DOM object

  1. The object obtained with native JS is DOM object
  2. The element obtained by jQuery method is jQuery object.
  3. The essence of jQuery object is: using $to package DOM object to generate object (pseudo array storage).
//1. DOM object
var myDiv = document.querySelector('div');// Mydiv is a DOM object
//2. JQuery object
//3. JQuery objects can only use jQuery methods, and DOM can only use native JS attribute methods

DOM objects and jQuery objects can be converted to each other.

Because native JS is bigger than jQuery, some native properties and methods of jQuery are not encapsulated. To use these properties and methods, we need to convert jQuery object into DOM object.

1. DOM to jQuery object: $(DOM object)


2. Transforming jQuery object into DOM object (two ways)

$('div ') [index] index is the index number

$('div '). Get (index) index is the index number
<video muted></video>
    //1. Convert DOM object to jQuery object
    //(1) we get the video directly and get the jQuery object
    // $('video');
    //(2) we have used native JS to get DOM objects
    var myvideo = document.querySelector('video');
    // $(myvideo).play();   There is no play in jQuery
    //2. Transform jQuery object into DOM object
    // myvideo.play();

2. Common API

1. JQuery selector

There are many ways for native JS to obtain elements, which are very miscellaneous and inconsistent in compatibility. Therefore, jQuery encapsulates the elements to make them unified.

$("selector") // the selector can write CSS selector directly
name usage describe
ID Selector $(‘#id’) Gets the specified ID element
Select all selector $(‘*’) Match all elements
Class selector $(‘class’) Get class elements of the same class
tag chooser $(‘div’) Get the elements of the same class
Union selector $(‘div,p,li’) Select multiple elements
Intersection selector $(‘li.current’) Intersection element
Descendant selector $(‘ul>li’) Use the > sign to get the parent son level elements, but not the grandson level elements
Descendant Selectors $(‘ul li’) Use space to get all Li elements under UL, including Sun Tzu, etc

1. Implicit iteration (important)

The process of traversing the internal DOM elements (stored as pseudo arrays) is called implicit iteration.

Simple understanding: loop traversal for all matched elements, execute corresponding methods, and do not need us to loop again, so as to simplify our operation and facilitate our call.

< div > surprise no, surprise no < / div >
< div > surprise no, surprise no < / div >
< div > surprise no, surprise no < / div >
< div > surprise no, surprise no < / div >
    <li>Same operation</li>
    <li>Same operation</li>
    <li>Same operation</li>
    //1. Get four div elements 

    //2. Set the background color to pink for the four divs. JQuery objects cannot use style
    $("div").css("background", "pink");
    //3. Implicit iteration is the method of traversing all matched elements and adding CSS to each element
    $("ul li").css("color", "red");

Case: drop down menu

2. JQuery filter selector

JQuery notes collation tutorial (common API and foundation)

$(function() {
        $("ul li:first").css("color", "red");
        $("ul li:eq(2)").css("color", "blue");
        $("ol li:odd").css("color", "skyblue");
        $("ol li:even").css("color", "pink");

JQuery notes collation tutorial (common API and foundation)

<div class="yeye">
    <div class="father">
        < div class = "son" > son < / div >

<div class="nav">
    <p>I'm a fart</p>
        <p>I'm P</p>
    //Note that all methods are in parentheses
    $(function() {
        //1. The parent() returns the parent element of the nearest level
        //If there are multiple parents, you can use parents ()
        //2. The seeds
        //(1) children () is similar to UL > Li
        $(".nav").children("p").css("color", "red");
        //(2) you can choose all the children in it, including your son and grandson. Find () is similar to the descendant selector
        $(".nav").find("p").css("color", "red");
        //3. Brother
        <li>I'm my li</li>
        <li>I'm my li</li>
        < Li class = "item" > I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
        <li>I'm my li</li>
    < div class = "current" > I have current < / div >
    < div > current
    //Note that all methods are in parentheses
$(function() {
    //1. Siblings all siblings except their own
    $("ol .item").siblings("li").css("color", "red");
    //2. The nth element
    var index = 2;
    //(1) we can choose by means of selector
     $("ul li:eq(2)").css("color", "blue");
   // $("ul li:eq(index)").css("color", "blue");
    //(2) we can use the method of choice to choose the more recommended way of writing
    $("ul li").eq(2).css("color", "blue");
     //$("ul li").eq(index).css("color", "blue");
    //3. Judge whether there is a class name

Remember: parent() children() find() siblings() EQ ()

3. The exclusive thought of jQuery

$(function() {
    //1. Implicit iteration binds click events to all buttons
    $("button").click(function() {
        //2. The current element changes the background color
        $(this).css("background", "pink");
        //3. The rest of the brothers remove the background color and iterate implicitly
        $(this).siblings("button").css("background", "");

Case: Taobao clothing

4. Chain programming of jquery

Chain programming is to save code and look more elegant

$(this).css("color","red").siblings().css("color","");// My color is red, brother node color is empty

$(this).siblings().css("color","red");// Brother, I will not change

$(this).siblings().parent().css("color","blue");// My brother's father changed color

2. JQuery style operation

1. How to operate CSS

JQuery can use CSS method to modify the style of simple elements; You can also manipulate classes to modify multiple styles.

1. If the parameter only writes the property name, it returns the property value


2. Parameters are attribute names, attribute values, separated by commas. They are used to set a set of styles. Attributes must be marked with mother numbers. If the value is a number, it can not be followed by units and quotation marks


3. Parameters can be in the form of objects, which is convenient for setting multiple styles. The attribute name and the attribute value are separated by colons, and the attribute may not be quoted,

//CSS method of operation style
$(function() {
    $("div").css("width", "300px");
    $("div").css("width", 300);
    $("div").css(height, "300px"); // Property names must be quoted
        width: 400,
        height: 400,
        backgroundColor: "red"
            //If it is a compound attribute, it must adopt hump naming method. If the value is not a number, it needs quotation marks

2. Set class style method

The function is the same as the previous classlist. You can operate the class style. Pay attention to the parameters in the operation class.

$("div").addClass("current"); // Add class

$("div").removeClass("current"); // Delete class

$("div").toggleClass("current");// Switch class

3. The difference between class operation and classname

The classname in native s will override the class name in the original element.

The class operation in jQuery only operates on the specified class, and does not affect the original class name.

// var one = document.querySelector(".one");
// one.className = "two";    The previous class name will be overridden
// $(".one").addClass("two");   This addclass is equivalent to appending the class name without affecting the previous class name

3. JQuery effect

JQuery encapsulates many animation effects, the most common of which are as follows:


JQuery notes collation tutorial (common API and foundation)

1. Show and hide effect


hide([speed],[easing],[fn]) ;

toggle([speed],[easing],[fn]) ;
  1. Parameters can be omitted and displayed directly without animation.
  2. Speed: a string (“slow”, “normal”, or “fast”) representing one of the three predetermined speeds or a millisecond value (e.g. 1000) representing the duration of the animation.
  3. Easing: (optional) used to specify the switching effect. The default is “swing”. The parameter “linear” can be used.
  4. FN: callback function, which is executed when the animation is finished, once per element.

Generally do not add parameters, because the animation is ugly

2. Sliding effect

slideDown([speed],[easing],[fn]) ); // slide downward
slideUp([speed],[easing],[fn]) ; // Slide up
slideToggle([speed],[easing],[fn]) ;// cut off
$("button").eq(2).click(function() {
    //Slide toggle ()

3. Event switching


Over: mouse over the element to trigger the function (equivalent to mouseenter)

Out: mouse out the function to be triggered by the element (equivalent to mouseleave)

$(function() {
    //Mouse past
    // $(".nav>li").mouseover(function() {
    //// $(this) the current element of jQuery, this, should not be quoted
    //// show() show element hide() hide element
    //     $(this).children("ul").slideDown(200);
    // });
    //// mouse away
    // $(".nav>li").mouseout(function() {
    //     $(this).children("ul").slideUp(200);
    // });
    //1. Event switch hover is the compound writing method of mouse passing and leaving
    // $(".nav>li").hover(function() {
    //     $(this).children("ul").slideDown(200);
    // }, function() {
    //     $(this).children("ul").slideUp(200);
    // });
    //2. Event switch hover if only one function is written, this function will be triggered when the mouse passes by or leaves
    $(".nav>li").hover(function() {

4. Animation queue and stop queue method

1. Animation or effect queue

Once the animation or effect is triggered, it will be executed. If it is triggered many times, it will cause multiple animations or effects to be executed in line.

2. Stop queuing

  1. The stop0 method is used to stop animation or effects.
  2. Note: stop is written in front of the animation or effect, which is equivalent to stopping the last animation.
$(".nav>li").hover(function() {
    //The stop method must be written before the animation

5. Fade in and fade out


1. Gradually adjust to the specified opacity

Fadeto ([speed], opacity, [easing], [FN]) // modify opacity

//Opacity transparency must be written, and the value is between 0 and 1.

Case 3: Highlight

6. Custom animation


Params: you want to change the style property. It is passed as an object and must be written. The attribute name can be without quotation marks. If it is a composite attribute, it needs to adopt the hump naming method borderLeft. Other parameters can be omitted.

Case: accordion effect of King glory

4. JQuery attribute operation

1. Set or get the intrinsic attribute value prop ()

The so-called intrinsic attribute of an element is its own attribute, such asFor example, the type in the < input > element.

Prop ("property") // get the property

Prop ("property", "property value") // set property

2. Set and get element custom attribute value attr ()

The attributes that users add to elements are called custom attributes. For example, add index = 1 to Div.

Attr ("attribute") // similar to native getattribute ()

Attr ("attribute", "attribute value") // similar to native setAttribute ()

You can also get H5 custom attributes by changing the method

3. Data cache data ()

The data () method can access data on the specified element without modifying the DOM element structure. Once the page is refreshed, the previously stored data will be removed.

Data ("name", "value") // attach data to the selected element

Data ("name") // get data from the selected element

At the same time, you can also read the HTML5 custom attribute data index, and the result is digital

<a href=" http://www.itcast.cn "> all very good</a>
<input type="checkbox" name="" id="" checked>
< div index = "1" data index = "2" > I'm div < / div >
$(function() {
    //1. Element.prop ("attribute name") gets the intrinsic attribute value of the element
    $("a"). Prop ("title", "we're all fine");
    $("input").change(function() {
    // console.log($("div").prop("index"));
    //2. We use attr ()
    $("div").attr("index", 4);
    //3. The data in the data cache data () is stored in the memory of the element
    $("span").data("uname", "andy");
    //This method gets the data index H5 custom attribute. The first one does not need to write data - and the return is numeric

5. JQuery text attribute value

Mainly for the content of the element and the value operation of the form

1. Common element content HTM () (equivalent to native innerHTML)
HTML () // get element content
HTML ("content") // set element content

2. Ordinary element text content text () (equivalent to native innerText)
Text ("content")

3. Val () of the form (equivalent to native value)
Val ("content")

To fixed (2): keep two decimal places

var price = (a*b).toFixed(2);

6. JQuery element operation

It mainly includes traversal, creation, addition and deletion of elements.

1. Traverse elements

JQuery implicit iteration is to do the same operation on the same kind of elements. If you want to do different operations for the same kind of elements, you need to use traversal.


1. Each0 method traverses every matched element. It is mainly processed by Dom. Each

2. The callback function has two parameters: index is the index number of each element;DEM ele is a DOM element object, not a jQuery object

    $(function() {
        // $("div").css("color", "red");
        //If you do different operations for the same type of elements, you need to use traversal elements (similar to for, but more powerful than for)
        var sum = 0;
        //1. Each () method traverses the element 
        var arr = ["red", "green", "blue"];
        $("div").each(function(i, domEle) {
            //The first parameter of the callback function must be the index number. You can specify the index number and name yourself
            // console.log(index);
            // console.log(i);
            //The second parameter of callback function must be DOM element, and the object is also named by itself
            // console.log(domEle);
            // domEle.css("color");  DOM objects have no CSS methods
            $(domEle).css("color", arr[i]);
            sum += parseInt($(domEle).text());// Converts a string to an integer    
        //2. $. Each () method traversal element is mainly used to traverse data and process data
         $.each($("div"), function(i, ele) {
        //     console.log(i);
        //     console.log(ele);
        // });
         $.each(arr, function(i, ele) {
        //     console.log(i);
        //     console.log(ele);
        // })
            name: "andy",
            age: 18
        }, function(i, ele) {
            console.log(i); //  The output is the name of the name age property
            console.log(ele); //  The output is the value of the Andy 18 attribute

2. Generation of elements

$("<li></li>"); // Create element

<!-- 1. Internal addition -- >
Element. Append ("content") // add it internally and put it behind it, similar to appendChild
Element. Prepend ("content")// Add inside, put in front

<!-- 2. External addition -- >
Element. After ("content")// Put the content in front of the target element
Element. Before ("content")// Put the content after the target element

<!-- 3. Delete element -- >
Element. Remove() // delete the matching element (itself)
Element. Empty() // delete all the child nodes in the matched element set
Element. HTML (") // you can delete all the child nodes in the matched element collection and empty the matched content

Internal elements are added. After generation, they are parent-child relationship.

External elements are added. After generation, they are brothers.

7. JQuery event operation

1. Single event registration

Element. Event (function () {})

$("div"). Click (functon() {event handler})

Other events are basically the same as native events

For example, mouseover, mouseou, blur, focus, change, Keydown, Keyup, reset, scroll, etc

2. Event handling on () binding event

The on () method binds the event handler of one or more events on the matching element

  1. Events: – one or more event types separated by spaces, “click” or “Keydown”
  2. Selector: the child element selector of the element.
  3. FN: the callback function is the listening function bound to the element.

    mouseenter: function () {
        $(this).css("backgroundColor", "blue");
    click: function () {
        $(this).css("backgroundColor", "pink");
    mouseleave: function () {
        $(this).css("backgroundColor", "green");
<!-- The second -- >
$("div").on("mouseover mouseleave", function () {

The advantage of on () method is 2

You can delegate actions to events. The definition of event delegation is to bind the event originally added to the child element to the parent element, that is, to delegate the event to the parent element.

$("div").on("mouseover mouseleave", function () {

//UL has a click event, but if you click Li, it will bubble to the parent UL and execute the click event
    alert('hello world');

//(3) on can bind events to dynamically created elements in the future
// $("ol li").click(function() {
//     alert(11);
// })
$("ol").on("click", "li", function() {
Var Li = $("< li > I created it later < / Li >");

Before that, there were methods such as bind, live (delegate()) to handle event binding or event delegation. In the latest version, please replace them with on.

Case JS code:

JQuery notes collation tutorial (common API and foundation)

$(function () {
    //1. Click the Publish button to dynamically create a small Li, put the content in the text box and delete button, and add it to UL
    $(".btn").on("click", function () {
        var li = $("<li></li>");
        li.html($(".txt").val() + "<a href='javascript:;'>  Delete < / a > ");

    //2. Click the delete button to delete the current microblog message
    //$("UL a"). Click (function() {// click at this time cannot add events to dynamically created a
    //     alert(11);
    // })
    //On can bind events to dynamically created elements
    $("ul").on("click", "a", function () {
        $(this).parent().slideUp(function () {

3. Event handling off () unbinding event

The on () method removes the event handler that was added by the on () method.

$("P"). Off() // unbinds the event handler of the P element
$("P"). Off ("click") // unbind the click event on the P element
$("ul").off("click","li");  // Unbinding event delegation
    $(function() {
            click: function() {
                Console.log ("I click");
            mouseover: function() {
                Console.log ('My mouse passed ');
        $("ul").on("click", "li", function() {
        //1. Event unbinding off 
        // $("div").off();  //  This is the release of all events on Div
        $("div").off("click"); //  This is to remove the click event from Div
        $("ul").off("click", "li");
        //2. One () but it can only trigger an event once
        $("p").one("click", function() {

    <li>We are all good children</li>
    <li>We are all good children</li>
    <li>We are all good children</li>
<p>I'm a fart</p>

4. Trigger ()

Some events want to be triggered automatically. For example, the auto play function of the carousel chart is the same as clicking the right button. The timer can automatically trigger the right button click event without mouse click.

Element. Click() // the first shorthand mode

Element. Trigger ("type") // the second automatic trigger mode

$("p").trigger("click"); // At this time, the click event will be triggered automatically without mouse click

$("div").on("click", function () {
//Auto trigger event
//1. Element. Event ()
 $("div").click();// Triggers the default behavior of the element
//2. Element. Trigger ("event")
$("div").trigger("click");// Triggers the default behavior of the element
//3. Element. Trigger handler ("event") is the default behavior that does not trigger an element
$("input").on("focus", function () {
    $(this). Val ("how are you?";

5. Jqurey event object

When an event is triggered, an event object is generated

Prevent default behavior:event.preventDefaultorreturn false

Prevent bubbling:event.stopPropagation

$(function() {
    $(document).on("click", function() {
        Console.log ("click document");

    $("div").on("click", function(event) {
        // console.log(event);
        Console.log ("div click");
        event.stopPropagation();// Prevent events from bubbling

8. JQuery size and position operation

1. Size

JQuery notes collation tutorial (common API and foundation)

  • If the above parameters are empty, the corresponding value will be obtained and the returned value will be numeric.
  • If the parameter is a number, modify the corresponding value.
  • Parameters may not be written in units

2. Location

There are three main positions: offset (), position (), scrolltop () / scrollleft ()


  1. The offset () method sets or returns the offset coordinates of the selected element relative to the document, which has nothing to do with the parent.
  2. This method has two attributes: left and top. Offset (). Top is used to get the distance from the top of the document, and offset (). Left is used to get the distance from the left side of the document.
  3. You can set the offset of the element: offset ({top: 10, left: 30});


The position method is used to return the offset coordinates of the selected element relative to the parent with positioning. If the parent has no positioning, the document will prevail.


Set or get the header and left side of the rolled element (document)

Other methods of jquery

1. JQuery copy object

If you want to copy (merge) one object to another, you can use the $. Extend () method

  1. Deep: if it is set to true, it means deep copy, and the default is false, shallow copy
  2. Target: target object to copy
  3. Object1: the object to be copied to the first object.
  4. Objectn: the object to be copied to the nth object.
  5. Shallow copy is to copy the address in the complex data type of the copied object to the target object. Modifying the target object will affect the copied object.
  6. Deep copy, adding true before, full clone (copied object, not address). Modifying the target object will not affect the copied object
//1. Usage
var targetObj = {};
var obj = {
    id: 1,
    name: "andy"
// $.extend(target, obj);
$.extend(targetObj, obj);
console.log(targetObj); //Objext(id:1,name:"andy")

//2. If targetobj has data
var targetObj = {
    id: 0
var obj = {
    id: 1,
    name: "andy"
// $.extend(target, obj);
$.extend(targetObj, obj);
console.log(targetObj); //  It will cover the original data object (ID: "1", name: "Andy") in targetobj

//3. There is no addition, but some coverage
var targetObj = {
    id: 0,
    msg: {
        Sex: 'male'
var obj = {
    id: 1,
    name: "andy",
    msg: {
        age: 18
// $.extend(target, obj);
$.extend(targetObj, obj);
console.log(targetObj); //  It will cover the original data in targetobj

Deep copy and shallow copy

Shallow copy only copies the address copy. If you modify the msg.name of targetobj, the msg.name of obj will also change, because they correspond to the same address

 $.extend(targetObj, obj);

JQuery notes collation tutorial (common API and foundation)

Deep copy, adding true before, full clone (copied object, not address). Modifying the target object will not affect the copied object

$.extend(true, targetObj, obj);

JQuery notes collation tutorial (common API and foundation)

2. Coexistence of multiple databases

JQuery uses $as identifier. With the popularity of jQuery, other JS libraries will also use this $as identifier, which will cause conflicts.

We need a solution, so that jQuery and other JS libraries do not conflict and can exist at the same time. This is called multi library coexistence.


JQuery notes collation tutorial (common API and foundation)

$(function() {
    function $(ele) {
        return document.querySelector(ele);
    //1. If the $symbol conflicts, we use jQuery
    //2. Let jQuery release its control over $and let it decide for itself
    var suibian = jQuery.noConflict();

3. JQuery plug in

JQuery function is relatively limited, you can use jQuery plug-in to achieve more complex effects.

Note: these plug-ins also rely on jQuery to complete, so you must first introduce jQuery files, so they are also called jQuery plug-ins. Common websites for jQuery plug-ins:

  1. JQuery plug in Libraryhttp://www.jq22.com/
  2. JQuery homehttp://www.htmleaf.com/

Steps for using jQuery plug-in:

1. Introduce relevant documents( JQuery file and plug-in file)

2. Copy relevant HTML, CSS, JS (call plug-in).

1. Picture loading

Lazy loading (pictures using delayed loading in can improve the speed of web page download. It also helps reduce server load)

When we slide the page to the viewable area, the image will be displayed.

We use the jQuery plug-in library easylazload. Note that the JS import file and JS call must be written at the end of the DOM element (image)

2. Full screen scrolling (fullpage. JS)

gitHub : https://github.com/alvarotrig…

Chinese translation website:http://www.dowebok.com/demo/2…

There are import files in the dist folder

3. Bootstrap JS plug in

Bootstrap framework also depends on jQuery development, so the JS plug-in must also introduce jQuery files.