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

$('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)
grammarusageexplain
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
                $(this).children('ul').show();
            })
            // Mouse away
            $('.nav>li').mouseout(function () {
                $(this).children('ul').hide();
            })
        })
(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:

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

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

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

  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
                $(this).toggleClass('current');
            })
        })

2.tab 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 () {
                $(this).addClass('current').siblings().removeClass('current');
                var index = $(this).index();
                $('.item').eq(index).show().siblings().hide();
            })
        })

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 () {
                    alert(1);
                });
            })
            $('button').eq(0).click(function () {
                $('div').show('slow');
            })
            $('button').eq(2).click(function () {
                $('div').toggle();
            })
        })

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

hover([over,]out)

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 () {
                    $('div').slideToggle();
                })
            })
        });

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 () {
                $("div").fadeIn(1000);
            })
            $('button').eq(1).click(function () {
                $("div").fadeOut();
            })
            $('button').eq(2).click(function () {
                $("div").fadeToggle();
            })
            $('button').eq(3).click(function () {
                // Speed and transparency must be written
                $("div").fadeTo(1000, .5);
            })
        })
(5) Custom animation

1.animate()

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 () {
                $("div").animate({
                    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
                $(this).stop().animate({
                    width: 224
                }).find(".small").stop().fadeOut().siblings(".big").stop().fadeIn();
                // 2. The width of other brothers becomes 69px, while the large picture fades out and the small picture fades in
                $(this).siblings("li").stop().animate({
                    width: 69
                }).find(".big").stop().fadeOut().siblings(".small").stop().fadeIn();
            })
        })

Note:

  • 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
    $('div').stop().slideToggle();
})

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 e.data("attribute name", "attribute value")

2. Get the attribute e.data("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>
<script>
    console.log($("div").data("index"));  //2
</script>
(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")

console.log($("div").html());
$("div").html("123");
(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()
        console.log($("div").text());
        $("div").text("123");      
(3) Form value (VAL)

Equivalent to value in native js

// 3. Form value (VAL)
        console.log($("input").val());
        $("input").val("123");
(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();
        nums++;
        $(this).siblings(".itxt").val(nums);
    });
    $(".decrement").click(function () {
        var nums = $(this).siblings(".itxt").val();
        if (nums == 1) {
            alert("The number of goods cannot be less than one");
        } else {
            nums--;
            $(this).siblings("input").val(nums);
        };
    });
(5) Returns the specified ancestor element

e.parents("selector")

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

    <script>
        console.log($(".four").parent().parent().parent());
        console.log($(".four").parents());
        console.log($(".four").parents(".one"));
    </script>
(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");
            $(this).val(1);
        } 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());
            })
            console.log(sum);

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) {
                console.log(i);
                console.log(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 () {
        $(this).parents(".cart-item").remove();
        getSum();
    })
    // (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
        $(".j-checkbox:checked").parents(".cart-item").remove();
        getSum();
    })
    // (3) Cleaning shopping cart
    $(".clear-all").click(function () {
        $(".cart-item-list").html("");
        getSum();
    })
(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) {
            $(".cart-item").addClass("check-cart-item");
        } else {
            $(".cart-item").removeClass("check-cart-item");
        }
        getSum();
    });

    // 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")) {
            $(this).parents(".cart-item").addClass("check-cart-item");
        } else {
            $(this).parents(".cart-item").removeClass("check-cart-item");
        }
        getSum();
    });
7. jQuery size, position and operation
(1) Dimensions
grammarmeaning
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()
            console.log($("div").width());
            // $("div").width(300);  // It is not necessary to write unit for parameters

            // 2.innerWidth()/innerHeight()  width+padding
            console.log($("div").innerWidth());

            // 3.outerWidth()/outerHeight()  width+padding+border
            console.log($("div").outerWidth());

            // 4.outerWidth(true)/outerHeight(true)  width+padding+border+margin
            console.log($("div").outerWidth(true));

(2) Location
grammarmeaning
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
            console.log($(".son").offset().top);

            $(".son").offset({
                left: 200,
                top: 200
            });

            // 2. Offset position() relative to the positioned parent
            // Note that this method can only get, not set
            console.log($(".son").position());
  • 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
            $(document).scrollTop(100);

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

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;
        toggleTool();
        function toggleTool() {
            if ($(document).scrollTop() >= boxTop) {
                $(".fixedtool").stop().fadeIn();
            } else {
                $(".fixedtool").stop().fadeOut();
            }
        };
        $(window).scroll(function () {
            toggleTool();
        })
    

    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
            $(this).addClass("current").siblings().removeClass("current");
        })
    
  • The page scrolls to a content area, and the current class name is added or deleted accordingly

    $(window).scroll(function () {
            toggleTool();
            // 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
            $("div").on({
                mouseenter: function () {
                    $(this).css("backgroundColor", "purple");
                },
                click: function () {
                    $(this).css("backgroundColor", "skyblue");
                }
            });
            // (2) Event handler consistency
            $("div").on("mouseenter mouseleave", function () {
                $(this).toggleClass("current");
            })

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 () {
                alert(11);
            })

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 () {
                alert(11);
            })
            var li = $("<li>I was founded later li</li>");
            $("ol").append(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>");
                $("ul").prepend(li);
                li.slideDown();
                $(".txt").val("");

            })
            // 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 () {
                    $(this).remove();
                });
            })
        })
(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 element.off("event", "child")
		$(function () {
            $("div").on({
                click: function () {
                    $(this).css("backgroundColor", "skyblue");
                },
                mouseover: function () {
                    $(this).css("backgroundColor", "purple");
                }
            })

            $("ul").on("click", "li", function () {
                alert(11);
            })

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

            // 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 () {
                alert(111);
            })
(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 () {
                alert(11);
            });
            // Auto trigger event
            // 1. element.event();
            $("div").click();
            // 2.element.trigger("event")
            $("div").trigger("click");
            // 3.element.triggerHandler("event")
            $("div").triggerHandler("click");
            
            // The trigger handler does not trigger the default behavior of the element
            $("input").on("focus", function () {
                $(this).val("how are you");
            })
            $("input").triggerHandler("focus");
        })
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);
            }
            console.log($("div"));
            $.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);
            }
            console.log($("div"));
            // $.each();  //error
            // 1. $if an error is reported, use jQuery
            jQuery.each();
            // 2. User defined jquery releases control over $
            var my = jQuery.noConflict();
            console.log(my("span"));
        })
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: http://www.jq22.com/
  • jQuery house: http://www.htmleaf.com/

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:https://github.com/alvarotrigo/fullPage.js
  • Chinese translation website: http://www.dowebok.com/demo/2014/77/
(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: http://www.todolist.cn/

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);
        console.log(data);
        console.log(data[0]["title"]);
(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();
            console.log(local);
            // 2. Append the new data to the local array and update it to the local storage
            local.push({ title: $(this).val(), done: false });
            saveData(local);
        }
    });

    // 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
        $("ol").empty();
        // 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
        saveData(data);
        // Re render page
        load();
    })
(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
        saveData(data);
        // Re render page
        load();
    })

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