Common jQuery API s and jQuery events

Keywords: Javascript Front-end JQuery

jQuery basic overview, please stamp: Overview and basic usage of jQuery

1, jQuery common API s

1. jQuery selector


(1) Basic selector:
  • ID selector: $("#id");
  • Select all:*
  • Class:
  • Labels: div
  • Union: div, span
  • Intersection: li.current
(2) Level selector:
  • Offspring: $("UL > Li");
  • Descendants: $("ul li");
(3) Implicit iteration (important)

The process of traversing the internal DOM elements (stored in the form of pseudo array) is called implicit iteration. The simple understanding is to loop through all the matched elements and execute the corresponding methods instead of looping ourselves, so as to simplify the operation.

(4) Filter selector (filter)

A filter is a string used to filter dom objects, which is used with selectors. After the dom object is selected, it is filtered.

Use the position of the dom object in the array as the filter condition.

  • First element: $('li:first ');
  • Last element: li:last
  • In the obtained li, the element with index number 2 (starting from 0): li:eq(2)
  • Elements with odd index numbers in the obtained li: li:odd
  • In the obtained li, elements with even index numbers: li:even
(5) Screening method (key)
parent()$('li').parent();Find parent
children(selector)$('ul').children('li');Equivalent to $('ul > Li '); Nearest level (son)
find(selector)$('ul').find('li');Equivalent to $('ul li '); Descendant Selectors
siblings(selector)$('.first').siblings('li');Finding sibling nodes does not include itself
nextAll([expr])$('.first').nextAll();Find all peer elements after the current element
prevAll([expr])$('.last').prevAll();Find all peer elements before the current element
hasClass(class)$('div').hasClass('protected');Check whether the current element contains a specific class. If so, return true
eq(index)$('li').eq(2);Equivalent to $('li: EQ (2)); Index starts at 0
(6) Sina drop-down menu
		$(function () {
            // Mouse passing
            $('.nav>li').mouseover(function () {
                // $(this) means to select the current element without quotation marks
                // show() display element
            // Mouse away
            $('.nav>li').mouseout(function () {
(7) Exclusive thought

In native js, it is the practice of "kill everyone and leave myself".

Set the current element style in jQuery, and clear the style for other sibling elements.

		$(function () {
            // 1. Implicit iteration: bind click events to all buttons
            $("button").click(function () {
                // 2. Change the background color of the current element
                $(this).css("background", "pink");
                // 3. Implicit iteration: remove the background color of other brothers
                $(this).siblings("button").css("background", "");
(8) Taobao clothing boutique demo
  • Retrieve the current index from the sidebar left
  • Then display the div corresponding to the current index
  • Then hide all the brothers of the div
		$(function () {
            $('#left li').mouseover(function () {
                var index = $(this).index();
                $('#content div').eq(index).show();
                $('#content div').eq(index).siblings('div').hide();
(9) Chain programming

Chain programming is to save code and look more elegant.

$(this).css('color','red).sibling().css('color',''); It means I turn red and my brother doesn't change color.

Equivalent to the following two lines of code:


When using chained programming, be sure to pay attention to which object executes the style.

2. jQuery style operation
(1) Manipulating CSS methods

Readable and writable;

  1. If the parameter only writes the property name, the property value is returned


  2. Modify the attribute. If the attribute value is a number, it can be without unit or quotation mark

    $(this).css('color', 'red');

  3. Parameters can be in the form of objects, which is convenient for setting multiple groups of styles

    $(this).css({'color':'white', 'backgroundColor':'pink'})

(2) Set class style method

1. The function is equivalent to the classList in the native js. You can manipulate the class style. Note that the parameters in the operation class do not add points.

  • Add class: addClass
  • Delete class: removeClass
  • Toggle class: toggleClass
	$(function () {
            $('div').click(function () {
                // 1. Add class
                // $(this).addClass('current');
                // 2. Delete class
                // $(this).removeClass('bor');
                // 3. Switching class
        }) bar switch demo:

  • Click li to make the current li add the current class and the other brothers remove the current class
  • Click to get li's index
  • Let the item of the corresponding index number below be displayed and the other items be hidden
	$(function () {
            $('li').click(function () {
                var index = $(this).index();

3. The difference between jQuery class operation and className

The className in the native js will overwrite the original class name of the element, while the class operation in jQuery only operates on the specified class and does not affect the original class name.

3. jQuery effect

jQuery encapsulates many animation effects for us. The most common are as follows:

(1) Show hide
  • show()

    show([speed, [easing], [fn]]) parameters can be omitted and displayed directly without animation

    speed: a string (slow, normal, fast) representing one of the three predetermined speeds or a millisecond value representing the animation duration (e.g. 1000)
    easing:(Optional) used to specify the switching effect. The default is swing. The parameter linear is available
    fn: callback function

  • hide()

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

  • toggle()

$(function () {
            $('button').eq(1).click(function () {
                $('div').hide(1000, function () {
            $('button').eq(0).click(function () {
            $('button').eq(2).click(function () {

However, in general, there are no parameters. Because the effect is ugly.

(2) Sliding: the parameters are the same as those displayed or hidden
  • slideDown()
  • slideUp()
  • slideToggle()
(3) Event switching


Over: move the mouse over the element to trigger the function (equivalent to mouseenter)
out: function to be triggered when the mouse moves away (equivalent to mouseleave)

	$(function () {
            // The two functions are triggered when the mouse passes and when the mouse leaves
            // $('button').hover(function () {
            //     $('div').slideDown();
            // }, function () {
            //     $('div').slideUp();
            // })

            // If only one function is written, this function will be triggered when the mouse passes and leaves
            $(function () {
                $('button').hover(function () {

Note that if only one function is written, this function will be triggered regardless of whether the mouse passes or leaves

(4) Fade in and out
  • fadeIn()

  • fadeOut()

  • fadeToggle()

  • fadeTo() modify transparency

    fadeTo([[speed], opacity, [easing], [fn]])

    opacity: transparency must be written. The value is between 0 and 1

		$(function () {
            $('button').eq(0).click(function () {
            $('button').eq(1).click(function () {
            $('button').eq(2).click(function () {
            $('button').eq(3).click(function () {
                // Speed and transparency must be written
                $("div").fadeTo(1000, .5);
(5) Custom animation


animate(params, [speed], [easing], [fn])

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

		$(function () {
            $("button").click(function () {
                    left: 500,
                    top: 300,
                    opacity: .4,
                    width: 400
                }, 500)
  • Note that params is stored as an object
  • Don't follow the unit

2. King glory accordion (folding card) demo

  • When the mouse passes li:
  • The current li width changes to 224px, while the small picture fades out and the large picture fades in;
  • The width of other pictures becomes 69px, and the large pictures fade out and the small pictures fade in
	$(function () {
            // Mouse over li
            $(".king li").mouseenter(function () {
                // 1. The width becomes 224px, and the small picture inside fades out and the large picture fades in
                    width: 224
                // 2. The width of other brothers becomes 69px, while the large picture fades out and the small picture fades in
                    width: 69


  • To change the width of small and big in a in li, you need to use the descendant selector find method, not the children method, because this method can only select the nearest descendant.
  • Chained programming can simplify the code. When small looks for big later, it uses the brother selector
  • Finally, add the stop method to the animation to stop the animation queue
(6) Animation queue and method of stopping queue

1. Once the animation or effect is triggered, it will be executed. If it is triggered multiple times, multiple animations or effects will be queued for execution.

The stop method stops the animation queue. Note that it should be written in front of the animation and end the last animation

$('button').hover(function () {
    // The stop method stops the animation queue. Note that it should be written in front of the animation

2. Highlight the demo

  • After the mouse passes, the transparency of other sibling elements of li is modified to 0.5; When the mouse leaves, it is changed to 1
  • Use hover to place the events triggered when the mouse passes and the events triggered when the mouse leaves
  • Be sure to add a stop method in front of the animation to stop the animation queue
$(".wrap li").hover(function () {
    $(this).siblings().stop().fadeTo(400, 0.5);
    }, function () {
    $(this).siblings().stop().fadeTo(400, 1);
4. jQuery property operation
(1) Sets or gets the element intrinsic attribute value prop()

The inherent attribute of an element is the attribute of the element itself, such as the href in the < a > element and the type in < input >

1. Get the attribute e.prop("attribute name") to get the attribute value

2. Set the attribute e.prop("attribute", "attribute value")

(2) Set or get element custom attribute()

1. Get the attribute e.attr("attribute name") and the user-defined attribute data in html5-

2. Set attribute e.attr("attribute", "attribute value")

(3) Data cache ()

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

1. Attach attribute"attribute name", "attribute value")

2. Get the attribute"attribute name")

3. You can also get the custom attribute data - in h5, but note that the attribute name does not need to contain data -, and the obtained attribute value is numeric

<div index="1" data-index="2">I am div</div>
    console.log($("div").data("index"));  //2
(4) Shopping cart demo – select all module

Select all ideas:

(1) The selection status of the three small check boxes inside follows the check all button
(2) Then use the prop() method to obtain the inherent property checked of the check box
(3) Assign the obtained select all button status to three small check boxes

// 1. Select all and deselect all buttons
    // Using change events
    $(".checkall").change(function () {
        var checked = $(this).prop("checked");
        // There are two select all buttons, both of which need to be changed; Select with union selector
        $(".j-checkbox, .checkall").prop("checked", checked);

If all the small check boxes are selected, the select all button also needs to be automatically selected:
(1) Each time you click the small check box button, you will judge the total number of small check boxes selected
(2) If it is exactly equal to 3, select the select all button; Otherwise, do not select

$(".j-checkbox").change(function () {
        // The: checked selector helps us select the selected check box element
        var nums = $(".j-checkbox:checked").length;
        // $(". j-checkbox").length counts the number of all small checkboxes
        if (nums === $(".j-checkbox").length) {
            $(".checkall").prop("checked", true);
        } else {
            $(".checkall").prop("checked", false);
5. jQuery content text value

It mainly operates on the content of the element and the value of the form.

(1) Common element content (HTML)

innerHTML, which is equivalent to native js, can get tags and content

Get element content (HTML)

Set element content html("content")

(2) Normal element text content ()

It is equivalent to innerText of native js and only gets the text

Get element text content text() set element text content text ("content")

// 2.text()
(3) Form value (VAL)

Equivalent to value in native js

// 3. Form value (VAL)
(4) Shopping cart demo – increase / decrease item quantity module

It is worth noting that:

  • When modifying the quantity, only the currently clicked commodity quantity will be modified, so select the sibling node of the clicked element
  • When reducing the quantity of goods, you need to judge whether the quantity is equal to 1. If it is equal to 1, you can't reduce it any more
// 2. Increase or decrease in commodity quantity
    $(".increment").click(function () {
        var nums = $(this).siblings("input").val();
    $(".decrement").click(function () {
        var nums = $(this).siblings(".itxt").val();
        if (nums == 1) {
            alert("The number of goods cannot be less than one");
        } else {
(5) Returns the specified ancestor element


	<div class="one">
        <div class="two">
            <div class="three">
                <div class="four">I'm on the fourth floor</div>

(6) Shopping cart demo – product subtotal module
  • Only the subtotal of this commodity can be modified
  • The unit price of the current commodity needs to be multiplied after removing the ¥ symbol, and the intercepted string substr(1) is used
  • You can return the specified ancestor element through parents()
  • If you want to keep two decimal places for the final calculation result, use the toFixed(2) method
// 3. Commodity subtotal module
    $(".increment, .decrement").click(function () {
        var nums = $(this).siblings("input").val();
        // var price = $(this).parent().parent().siblings(".p-price").text().substr(1);
        var price = $(this).parents(".p-num").siblings(".p-price").text().substr(1);
        var sum = (nums * price).toFixed(2);
        $(this).parent().parent().siblings(".p-sum").text('¥' + sum);
        $(this).parents(".p-sum").siblings(".p-sum").text('¥' + sum);

If you directly modify the values in the form, you also need to calculate the subtotal and use the form change event

// Directly modify the values in the form
    $(".itxt").change(function () {
        var nums = $(this).val();
        if (nums <= 0) {
            alert("The number of goods cannot be less than one");
        } else {
            var price = $(this).parents(".p-num").siblings(".p-price").text().substr(1);
            var sum = (nums * price).toFixed(2);
            $(this).parents(".p-num").siblings(".p-sum").text('¥' + sum);
6. jQuery element operation

It is mainly used to traverse, create, add and delete elements.

(1) Traversal

Implicit iteration in jQuery is to do the same operation on the same type of elements. If you want to do different operations on the same type of elements, you need to traverse.

Syntax 1: $("div"). Each (function (index, domelement) {XXX;}) traverses DOM elements

The two parameters in the callback function represent the index number of the element and each DOM element object respectively, which is not a jQuery object, so the jQuery method cannot be used. If you want to use the jQuery method, you need to convert it to a jQuery object first. And both parameters can be named by themselves.

// 1. The each() method traverses the element
            var arr = ["red", "green", "blue"];
            var sum = 0;
            $("div").each(function (i, domEle) {
                // console.log(i);
                // console.log(domEle);  //  The dom element is obtained, and the jquery method cannot be used
                // If you want to use the jquery method, you need to convert it to a jquery object first
                $(domEle).css("color", arr[i]);
                sum += parseInt($(domEle).text());

Syntax 2: $. Each (traversing objects, function(index, ele) {xxx;}) is mainly used to traverse data and process data, such as traversing arrays, objects, etc

// 2. The $. each() method is mainly used to traverse data and process data
            $.each(arr, function (i, ele) {
            $.each({ name: "andy", age: 22 }, function (i, ele) {
                console.log(i);  // Returns the property name
                console.log(ele);  //Return property value
(2) Shopping cart demo – calculates the total number of items and the total amount

Encapsulates a function used to calculate the total number and total price of goods. Then, it is called when increasing or decreasing the commodity quantity, manually modifying the commodity quantity, changing the selection of small check box and changing the selection of all check box.

// 4. Commodity total module
    function getSum() {
        var count = 0;  //Total 
        var money = 0;  //Total price
        $(".j-checkbox").each(function (i, ele) {
            if ($(ele).prop("checked")) {
                count += parseInt($(ele).parents(".cart-item").find(".itxt").val());
                money += parseFloat($(ele).parents(".cart-item").children(".p-sum").text().substr(1));
        $(".amount-sum em").text(count);
        $(".price-sum em").text('¥' + money.toFixed(2));
(3) Create, add, and delete

$("< li > < / Li >") will dynamically create a Li tag
e.append(li) e.prepend(li) add elements inside
e.before(div) e.after(div) add elements outside
e.remove() removes itself e.empty(), e.html("") removes child nodes, and deletes elements

		// 1. Create element
            var li = $("<li>I'm new li</li>");
            var div = $("<div>I'm new div</div>");

        // 2. Add element
            // (1) Add parent-child relationship internally
            // $("ul").append(li);  // Add at the end
            $("ul").prepend(li);  //Add at the beginning
            // (2) Add siblings externally
            // $("div").before(div);  // Add before
            $("div").after(div);  //Add after

        // 3. Delete element
            // $("div").remove();  // Delete itself
            // $("ul").empty();  // Delete child nodes in matching elements
            $("ul").html("");  //Delete child nodes in matching elements
(4) Shopping cart demo – delete shopping cart items
  • Use remove to delete the item
  • There are three places to delete: 1. The delete button after the item 2. Delete the selected item 3. Clean up the shopping cart
  • When deleting the selected item, there will be an implicit iterative process without writing the traversal
  • Note: after deleting goods, the total number and total amount of goods should be recalculated
// 5. Delete item
    // (1) Delete button after item
    $(".p-action a").click(function () {
    // (2) Delete selected item
    $(".remove-batch").click(function () {
        // There will be an implicit iteration to remove all the items in the selected small check box, and you do not need to write your own traversal function
    // (3) Cleaning shopping cart
    $(".clear-all").click(function () {
(5) Shopping cart demo – adds a background color to the selected item

When the selection status of the select all button and the small check box button changes, the check cart item class is added or removed according to whether it is currently selected

// 1. Select all and deselect all buttons
    // Using change events
    $(".checkall").change(function () {
        var checked = $(this).prop("checked");
        // There are two select all buttons, both of which need to be changed; Select with union selector
        $(".j-checkbox, .checkall").prop("checked", checked);
        if (checked) {
        } else {

    // Small check box
    $(".j-checkbox").change(function () {
        // The: checked selector helps us select the selected check box element
        var nums = $(".j-checkbox:checked").length;
        // $(". j-checkbox").length counts the number of all small checkboxes
        if (nums === $(".j-checkbox").length) {
            $(".checkall").prop("checked", true);
        } else {
            $(".checkall").prop("checked", false);
        if ($(this).prop("checked")) {
        } else {
7. jQuery size, position and operation
(1) Dimensions
width()/height()Gets and sets the element width/height. Only width/height is calculated
innerWidth()/innerHeight()Include padding
outerWidth()/outerHeight()Including padding + border
outerWidth(true)/outerHeight(true)Including padding + border + margin
			// 1.width()/height()
            // $("div").width(300);  // It is not necessary to write unit for parameters

            // 2.innerWidth()/innerHeight()  width+padding

            // 3.outerWidth()/outerHeight()  width+padding+border

            // 4.outerWidth(true)/outerHeight(true)  width+padding+border+margin

(2) Location
offset()Sets or gets the offset coordinate of the element relative to the document, regardless of the parent
position()Gets the offset coordinates of the element relative to the parent with positioning. If none of the parent has positioning, the document shall prevail
scrollTop()/scrollLeft()Gets or sets the header (or left side) where the element is rolled away
			// 1. Get or set the position (offset) offset() from the document
            console.log($(".son").offset());  // An object is returned

                left: 200,
                top: 200

            // 2. Offset position() relative to the positioned parent
            // Note that this method can only get, not set
  • Note that offset() returns an object, which is the offset coordinate of the element relative to the document; It can also be set with the offset() method
  • Because the object returned by offset() contains the top and left attributes, offset().top can return the distance from the top of the document separately
  • position() also returns the object, which is the offset coordinate of the element relative to the positioned parent; This method can only get, not set offset
			// You can set the rolled head

            // You can also get the rolled head
            var boxTop = $(".container").offset().top;
            $(window).scroll(function () {
                if ($(document).scrollTop() >= boxTop) {
                } else {

Top of return with animation: note that html and body elements must be animated here, not document documents

// Back to top
            $(".back").click(function () {
                // $(document).scrollTop(0);
                // Return to top with animation
                $("body, html").stop().animate({
                    scrollTop: 0
(3) Elevator navigation demo
  • First, scroll to the "recommended today" module and let the elevator navigation display

    // 1. Show / hide elevator navigation module
        var boxTop = $(".recom-hd").offset().top;
        function toggleTool() {
            if ($(document).scrollTop() >= boxTop) {
            } else {
        $(window).scroll(function () {

    Here, the elevator navigation scrolling is encapsulated into a function. As soon as the page is loaded, it scrolls to determine whether to display the elevator navigation.

  • Click the elevator navigation page to scroll to the corresponding content area

  • The elevator navigation module corresponds to the content area module one by one. When you click a small module of elevator navigation, you will get the index number of the current small module

  • You can calculate the distance that animate needs to move: offset().top of the current index number content area module

    // 2. Click the elevator navigation page to scroll to the corresponding content area
        $(".fixedtool li").click(function () {
            // Calculate where the page is going
            var curr = $(".floor .w").eq($(this).index()).offset().top;
            // Page animation scrolling
            $("body, html").stop().animate({
                scrollTop: curr
            // Let the currently clicked li add the class name, and the sibling node remove the class name
  • The page scrolls to a content area, and the current class name is added or deleted accordingly

    $(window).scroll(function () {
            // 3. The page scrolls to a content area, and the left elevator navigation li adds or deletes the current class name accordingly
            $(".floor .w").each(function (i, ele) {
                if ($(document).scrollTop() >= $(ele).offset().top) {
                    // console.log(i);  //index
                    $(".fixedtool li").eq(i).addClass("current").siblings().removeClass("current");

    It is necessary to determine the content area currently scrolled according to the scrolling event, so it should be written in the scrolling event. Get the index of the current content, and let the li in the corresponding elevator navigation add the current class name, and the other brothers remove the class name.

  • Use throttle valve to solve small bug s

    1,When clicked li After that, there is no need to perform page scrolling events li Add or remove current Class name
    2,Declare a throttle valve(It's actually a mutex),Only when flag=true The page scrolling event is executed only when
    3,But I clicked li After, close the throttle valve(flag=false)
    4,stay li After executing the animation, you have to animate Function, and then open the throttle valve. Otherwise, page scrolling will not work properly after clicking

2, jQuery event

1. jQuery event registration
(1) Single event registration

element. Event (function() {...})

The event type is basically the same as the native event type: for example, mouseover mouseout blur focus change keydown keyup resize scroll, etc

			$("div").click(function () {
                $(this).css("backgroundColor", "skyblue");
            $("div").mouseenter(function () {
                $(this).css("backgroundColor", "purple");
2. jQuery event handling
(1) Event handling on() binding event

element.on(events, [selector], fn)

  • Events: one or more events separated by spaces
  • Selector: the child element selector of the element
  • fn: callback function

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

// 2. Event handling
            // (1) Inconsistent event handlers
                mouseenter: function () {
                    $(this).css("backgroundColor", "purple");
                click: function () {
                    $(this).css("backgroundColor", "skyblue");
            // (2) Event handler consistency
            $("div").on("mouseenter mouseleave", function () {

If the event handling functions are inconsistent, they are written in the form of objects, and each event corresponds to a handling function.

2. You can delegate events. 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

// on() implements event delegation (delegation) 
            // The event is bound to ul, but the trigger object is li. The event bubbles on the parent element and executes the event
            $("ul").on("click", "li", function () {

3. For dynamically created elements, click() cannot bind events. on() can bind events to dynamically generated elements

// on() can bind events to dynamically created elements
            // $("ol li").click(function() {/ / traditional click events cannot bind to dynamically created elements in the future
            //     alert(1);
            // });
            $("ol").on("click", "li", function () {
            var li = $("<li>I was founded later li</li>");
(2) Microblog release effect demo
  • Click the Publish button to dynamically create a li, put the content in the text box and a delete button, and add the li to the ul
  • Click the delete button to delete the current microblog message: on binds events to dynamically created elements and uses event delegation
		$(function () {
            // 1. Click the Publish button to dynamically create li, put text content and delete button inside, and add li 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 li
            // Use on to bind events to dynamically created elements, and use event delegates
            $("ul").on("click", "a", function () {
                $(this).parent().slideUp(function () {
(3)off() unbinding event
  • You can release all events without parameters
  • You can also unassign a single event to have a parameter
  • You can also cancel the event delegate"event", "child")
		$(function () {
                click: function () {
                    $(this).css("backgroundColor", "skyblue");
                mouseover: function () {
                    $(this).css("backgroundColor", "purple");

            $("ul").on("click", "li", function () {

            // If there are no parameters, it means that all events on the div are released
            // $("div").off();
            // Release only div click events

            // Cancel event delegation
            $("ul").off("click", "li");

If some events want to be triggered only once, you can use one() to bind the event

// one() is triggered only once
            $("p").one("click", function () {
(4) Auto trigger event

Some events want to be triggered automatically. For example, the automatic playback function of the rotation chart is more consistent with clicking the button on the right. You can use the timer to automatically trigger the button click event on the right without clicking the mouse.

  • element.event()

  • element.trigger("event")

  • element.triggerHandler("event") this event does not trigger the default behavior of the element

    For example, when input gets the focus, the cursor flashes.

		$(function () {
            $("div").on("click", function () {
            // Auto trigger event
            // 1. element.event();
            // 2.element.trigger("event")
            // 3.element.triggerHandler("event")
            // The trigger handler does not trigger the default behavior of the element
            $("input").on("focus", function () {
                $(this).val("how are you");
3. jQuery event object

When the event is triggered, the event object will be generated, which is consistent with the use method of native js.

		$(function () {
            $(document).on("click", function (e) {
                console.log("Click document");
            $("div").on("click", function (e) {
                // console.log(e);
                console.log("Click div");
                e.stopPropagation();  //Stop bubbling

3, jQuery other methods

1. jQuery copy object

If you want to copy (merge) an object to another object, you can use the extend() method

$.extend([deep], target, object1, [objectN])

  • Deep: if set to true, it indicates deep copy, and the default is false, shallow copy
  • Target: the target object to copy
  • object1: the object to be copied

Shallow copy is to copy the address of complex data types in the copied object to the target object, that is, the copied object and the target object point to the same address, so modifying the target object will modify the original copied object at the same time.

Deep copy will completely copy the data inside to the target object. If there are non conflicting attributes in it, it will be merged together. The copy of complex data types does not directly copy the address, but reopens a new space.

2. Multi library coexistence

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

For example, in the following code, we encapsulate the $function as an element selector. When we use $for traversal, an error will be reported.

		$(function () {
            function $(ele) {
                return document.querySelector(ele);
            $.each();  //error

Therefore, we need a solution so that jQuery and other js libraries can exist at the same time without conflict, which is called multi library coexistence.

jQuery's solution:
  • Use jQuery instead of $, such as jQuery("div")
  • Use the jQuery.noConflict() method to let jQuery release the control of $, and the user-defined variables
$(function () {
            function $(ele) {
                return document.querySelector(ele);
            // $.each();  //error
            // 1. $if an error is reported, use jQuery
            // 2. User defined jquery releases control over $
            var my = jQuery.noConflict();
3. jQuery plug-in

JQuery has limited functions. If you want more complex special effects, you can complete them with the help of jQuery plug-in. Because these plug-ins depend on jQuery, they must first introduce jQuery files, so they are called jQuery plug-ins.

Common websites for jQuery plug-ins:

  • jQuery plug-in library:
  • jQuery house:

jQuery plug-in usage steps:

  • Import related files (jQuery files and plug-in files)
  • Copy relevant html, css and JS (call plug-in)
(1) Waterfall flow plug-in
(2) Lazy loading of pictures

Using delayed loading of images can improve the download speed of web pages and reduce the load on the server. When the page slides to the viewing area, the picture is displayed.

Use jquery plug-in to help us load images.

(3) Full screen scrolling plug-in (fullpage.js)
  • gitHub:
  • Chinese translation website:
(4)bootstrap js plug-in

The bootstrap framework also relies on jQuery development, so if you want to use the js plug-in inside, you must also introduce jQuery files.

4,toDoList demo
1,Enter the content in the text box and press enter to generate a to-do
2,Click the to-do check box to add the current data to the completed items
3,Click the completed items check box to add the current data to the to-do list
4,**The content of this page will not be lost**

Official website:

Using localStorage for storage, whether you press enter or click the check box, you load the locally stored data into the page, so as to ensure that the data will not be lost when refreshing and closing the page. Stored data format:``

(1) Locally stored data format

var todolist = [{title: 'xxx', done: false}]

Note that only string type data formats can be stored in local storage:

  • Therefore, you need to convert the data into a string before storing it in the local storage JSON.stringify()
  • When fetching data, first convert the data in the local storage into object format, and then take JSON.parse()
		var todolist = [{
            title: 'study',
            done: false
        }, {
            title: 'attend class;class begins',
            done: true
        // Local storage can only store string type data formats
        // localStorage.setItem("todo", todolist);
        // 1. First convert the data to string format JSON.stringify()
        localStorage.setItem("todo", JSON.stringify(todolist));
        var data = localStorage.getItem("todo");
        console.log(typeof data);
        // 2. Get the locally stored data and convert the string to JSON object format JSON.parse()
        data = JSON.parse(data);
(2) Press enter to add the new data to the local storage

The previous data is stored in memory, and refreshing the page will lead to data loss; The demo uses local storage so that refreshing the page will not lose data.

// 1. Press enter to store the data in the local storage
    $("#title").on("keydown", function (event) {
        // ASCII 13 for enter
        if (event.keyCode === 13) {
            // Read the original data in the local storage first
            var local = getData();
            // 2. Append the new data to the local array and update it to the local storage
            local.push({ title: $(this).val(), done: false });

    // Read locally stored data
    function getData() {
        var data = localStorage.getItem("todolist");
        if (data !== null) {
            // Converts the obtained string format to object format
            return JSON.parse(data);
        } else {
            return [];

    // Save data to local storage
    function saveData(data) {
        localStorage.setItem("todolist", JSON.stringify(data));
(3) Load locally stored rendering data into the page

Note that before each rendering, you need to empty the contents of the original ol, and then render and load the latest data. Call after pressing enter and the page has just been loaded.

// Render load data
    function load() {
        // Read local data
        var data = getData();
        // console.log(data);
        // Before traversal, you need to empty the element content in ol, otherwise the original element will be rendered twice
        // Traversal data
        $.each(data, function (i, n) {
            // console.log(n);
            $("ol").prepend("<li><input type='checkbox'> <p>" + n.title + "</p> <a href='javascript:;></a></li>")
(4) Delete operation

Instead of deleting li, delete the data stored locally. First obtain the local storage data, delete the corresponding data, save it to the local storage, and re render the list li.

Give each delete link a user-defined index. Click Delete to delete the corresponding li.

// 4. Delete
    $("ol").on("click", "a", function () {
        // Get local storage first
        var data = getData();
        // Modify data
        var index = $(this).attr("id");  //Find the index that needs to be deleted
        data.splice(index, 1);  //Delete array element splice(index, n) number of elements deleted by index
        // Save to local storage
        // Re render page
(5) Selection in progress and completed

Click the check box to modify the done attribute of the corresponding data (in local storage), and then re render the data list.

1,Click to get the local stored data
2,Modify corresponding data attributes done,And assigned to the of the check box checked state
3,Save data to local storage
4,Re render and load the data list, load Add a new condition in the function if the current data done by true,Just load the list rendering into ul inside(Completed);Otherwise, put it in ol in
// 5. Ongoing and completed options
    $("ol, ul").on("click", "input", function () {
        // Get locally stored data
        var data = getData();
        // Modify data
        var index = $(this).siblings("a").attr("id");
        data[index].done = $(this).prop("checked");
        // Save to local storage
        // Re render page

Posted by Carline on Mon, 11 Oct 2021 15:28:15 -0700