JQuery tutorial (from Beginner to Master)

[TOC]

JQuery documents, events, animations

1. Document processing – adding, deleting and modifying

Document handling methods describe
Internal insert append() Appends content inside each matched element
appendTo() Appends all matched elements to another specified set of element elements
prepend() Prepend content inside each matched element
prependTo() Prefixes all matched elements to another, specified set of element elements
External insert after() Insert content after each matched element
before() Insert content before each matched element
insertAfter() Inserts all matching elements after another, specified set of elements
insertBefore() Inserts all matched elements in front of another, specified set of elements
The parcel wrap() Wrap all matching elements around structured tags of other elements
unwrap() This method removes the parent element of the element
wrapAll() Wrap all matched elements in a single element
wrapInner() Wrap the child content (including text nodes) of each matched element in an HTML structure
replace replaceWith() Replaces all matched elements with the specified HTML or DOM element
replaceAll() Replaces all matched elements with matched elements
delete empty() Deletes all child nodes in the matching set of elements
remove() Remove all matching elements from the DOM
detach() Remove all matching elements from the DOM
cloning clone() Clone the matching DOM elements and select the cloned copies

Append, appendTo

// 1. Add span to ul (ul1)
/ / $(' # ul1). Append (' < span > append added span < / span > ');
$('appendTo add span').appendTo($('#ul1'));
Copy the code

The prepend, prependTo

// add span to ul (ul1)
/ / $(' # ul1). The prepend (' < span > add the span of the prepend < / span > ');
$('prependTo add span').prependTo($('#ul1'));
Copy the code

Before, insertBefore

// 3. Add span before li (whose title is hello) under ul with id ul1
/ / $(' # ul1) children (' li [the title = hello]), before (' < span > before adding the span of < / span > ');
$('insertBefore add span').insertBefore($('#ul1').children('li[title=hello]'));
Copy the code

After, insertAfter

// 4. Add span after li (title is hello) under ul with id ul1
/ / $(' # ul1) children (' li [the title = hello] '). After (' < span > after adding the span of < / span > ');
$('insertAfter add span').insertAfter($('#ul1').children('li[title=hello]'));
Copy the code

ReplaceWith, replaceAll

// 5. Replace all the li (title is hello) of ul with p
/ / $(' # ul2.) children (' li [the title = hello] '). The replaceWith (' < p > replaceWith replace p < / p > ');
$('

replaceWith replaced p

'
).replaceAll($('#ul2').children('li[title=hello]')); Copy the code

Empty, remove, detach

// 6. Remove all li from ul whose ID is UL2
$('#ul2').children('li').empty(); // The contents of li in ul2 are cleared
Copy the code

// $('#ul2').empty(); // All child elements are removed
// $('#ul2>*').remove(); // All child elements are removed
// $('#ul2').children('li').remove();
$('#ul2').children('li').detach();
Copy the code

Exercise: Adding and removing employees

The HTML code

<table id="employeeTable">
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Salary</th>
        <th>&nbsp;</th>
    </tr>
    <tr>
        <td>Tom</td>
        <td>[email protected]</td>
        <td>5000</td>
        <td><a href="deleteEmp? id=001">Delete</a></td>
    </tr>
    <tr>
        <td>Jerry</td>
        <td>[email protected]</td>
        <td>8000</td>
        <td><a href="deleteEmp? id=002">Delete</a></td>
    </tr>
    <tr>
        <td>Bob</td>
        <td>[email protected]</td>
        <td>10000</td>
        <td><a href="deleteEmp? id=003">Delete</a></td>
    </tr>
</table>

<div id="formDiv">
    <h4>Add new employees</h4>
    <table>
        <tr>
            <td class="word">name:</td>
            <td class="inp">
                <input type="text" name="empName" id="empName"/>
            </td>
        </tr>
        <tr>
            <td class="word">email:</td>
            <td class="inp">
                <input type="text" name="email" id="email"/>
            </td>
        </tr>
        <tr>
            <td class="word">salary:</td>
            <td class="inp">
                <input type="text" name="salary" id="salary"/>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <button id="addEmpButton" value="abc">
                    Submit
                </button>
            </td>
        </tr>
    </table>
</div>
Copy the code

JQuery code

/ / add
$('#addEmpButton').click(function () {
    // Get input
    var $empName = $('#empName');
    var $email = $('#email');
    var $salary = $('#salary');
    var empName = $empName.val();
    var email = $email.val();
    var salary = $salary.val();
    // Insert input
    $('<tr></tr>')
        .append('<td>' + empName + '</td>')
        .append('<td>' + email + '</td>')
        .append('<td>' + salary + '</td>')
        .append(' + Date.now() + '">Delete</a></td>')
        .appendTo($('#employeeTable').children('tbody')); // Insert under tBody generated by default
    // Clear the input
    $empName.val(' ');
    $email.val(' ');
    $salary.val(' ');
});

/ / delete
// Use event delegate so that even subsequent additions are bound to the corresponding event
// Otherwise, you need to manually add click events when adding elements. Learn about event broker/delegate/delegate below
$('#employeeTable').delegate('a'."click".function () { 
    var $tr = $(this).parent().parent();
    var name = $tr.children(':first').html();
    if (confirm('Sure to delete' + name + About '? ')) {
        $tr.remove();
    }
    return false;
});
Copy the code

The effect

2. Event handling

Event method describe
Page load ready() Bind a function to execute when the DOM is loaded and ready to be queried and manipulated
The event processing on() An event handler that binds one or more events to a selection element
off() An event handler that removes one or more events from a selection element
bind() Bind event handlers to a specific event for each matched element
unbind() The reverse of bind() removes the bound event from each matched element
one() Bind a one-time event handler to a specific event (like click) for each matched element
trigger() Fires some kind of event on each matched element
triggerHandler() This particular method fires all bound handlers for the specified event type. The default browser actions are not performed, and events do not bubble up
Event delegate delegate() The specified element (a child of the selected element) adds one or more event handlers and specifies the functions to run when those events occur
undelegate() Removes one or more event handlers added by the delegate() method
Events to switch hover() A method that mimics a hover event (when the mouse moves over and out of an object)
toggle() Used to bind two or more event handler functions in response to a rotating click event for the selected element
The event focus(),focusin() Focus, FocusIn events are emitted when the element gains focus
blur(),focusout() Blur and FocusOut events are emitted when an element loses focus
change() The change event occurs when the value of an element changes
click() Fires a click event for each matched element
dblclick() When you double-click an element, a DBLClick event occurs
error() An error event occurs when an element encounters an error (not properly loaded)
mousedown() A MouseDown event occurs when the mouse pointer is moved over the element and the mouse button is pressed
mouseup() A Mouseup event occurs when the mouse button is released on the element
mouseenter() The mouseEnter event occurs when the mouse pointer passes over the element
mouseleave() The mouseleave event occurs when the mouse pointer leaves the element
mouseover() A mouseover event occurs when the mouse pointer is over an element
mouseout() A mouseout event occurs when the mouse pointer is removed from an element
mousemove() The Mousemove event occurs when the mouse pointer moves within the specified element
keypress() A keyPress event occurs when the keyboard or button is pressed
keydown() A keyDown event occurs when the keyboard or button is pressed
keyup() A keyUp event occurs when the button is released
resize() The resize event occurs when the browser window is resized
scroll() The Scroll event occurs when the user scrolls the specified element
select() A SELECT event occurs when the text in an input element of textaREA or text type is selected
submit() A Submit event occurs when the form is submitted
unload() An Unload event occurs when the user leaves the page

Click, on, bind

// 1. Bind listener to.out (bind in two ways)
// $('.outer').click(function () {
// alert('click outer');
// });
// $('.outer').on('click', function () {
// alert('click outer');
// });
$('.outer').bind('click'.function () {
    alert('click outer');
});
Copy the code

Mouseenter, mouseleave, hover

// 2. Bind mouse in and out events to. Inner
// $('.inner')
// .mouseenter(function () {
// alert('mouse enter');
/ /})
// .mouseleave(function () {
// alert('mouse leave');
/ /});
$('.inner').hover(
    function () {
        alert('mouse enter');
    }, function () {
        alert('mouse leave');
    });
Copy the code

Mouseover and mouseout

The difference between mouseover/mouseout and mouseEnter /mouseleave is the child element

  • mouseover/mouseoutEntry and exit child elements are triggered again
  • mouseenter/mouseleaveEntering and leaving child elements will not trigger again
$('.outer')
    .bind('mouseover'.function () {
    console.log('mouse over');
})
    .bind('mouseout'.function () {
    console.log('mouse out');
});
Copy the code

Off, unbind

// 3. Click btn1 to remove all event listening on inner
$('#btn1').on('click'.function () {
    // $('.inner').off();
    $('.inner').unbind();
});

// 4. Click btn2 to remove the mouseEnter event on inner
$('#btn2').on('click'.function () {
    // $('.inner').off('mouseenter');
    $('.inner').unbind('mouseenter');
});
Copy the code

Extra knowledge

OffsetX, offsetY, pageX, pageY, clientX, clientY

  • offsetX,offsetY: Coordinates relative to the event object that triggered the event
  • pageX,pageY: Coordinates relative to the viewport
  • clientX,clientY: Coordinates relative to the screen
// 5. Click btn3 to get the event coordinates
$('#btn3').on('click'.function (event) {
    console.log('[' + event.offsetX + ', ' + event.offsetY + '] '); / / [54, 8]
    console.log('[' + event.pageX + ', ' + event.pageY + '] '); / / [349, 259]
    console.log('[' + event.clientX + ', ' + event.clientY + '] '); / / [349, 59]
});
Copy the code

StopPropagation, the preventDefault

// 6. Click. Inner area, external click listener does not respond
$('.inner').on('click'.function (event) {
    alert('click inner');
    event.stopPropagation(); // Stop bubbling
});

// 7. Click the link and do not jump if the current time is even
$('#test4').on('click'.function (event) {
    if (Date.now() % 2= = =0) {
        event.preventDefault(); // Prevent default behavior}})Copy the code

3. Event delegate (delegate/proxy)

We have already used event delegation in the Exercise: Adding and Removing employees. So what exactly is an event delegate?

Event delegation

Delegate event listening for multiple child elements to parent elements, on which listener callbacks are applied

When operating on any child element, events bubble up to the parent element

The parent element does not handle the event directly. Instead, it gets the child element from which the event occurred and calls the callback from that child element

Benefits of event delegation

  • New child elements are added, and the event response is handled automatically
  • Reduce the number of event listeners: n==>1

Event delegate API

The delegate, undelegate

  • Set event delegate:$(parentSelector).delegate(childrenSelector, eventName, callback)
  • Remove event delegate:$(parentSelector).undelegate(eventName)
// Click li to change the background to red
$('ul').delegate('li'.'click'.function () {
    this.style.backgroundColor = 'red';
});

// Click btn1 to add a li
$('#btn1').on('click'.function () {$('ul').append('
  • add li...
  • '
    ); }); $('#btn2').on('click'.function () {$('ul').undelegate('click'); }); Copy the code

    Practice: Cut diagrams

    The HTML code

    <div id="container">
        <div id="list">
            <img src="img/5.jpg" alt="5"/>
            <img src="img/1.jpg" alt="1"/>
            <img src="img/2.jpg" alt="2"/>
            <img src="img/3.jpg" alt="3"/>
            <img src="img/4.jpg" alt="4"/>
            <img src="img/5.jpg" alt="5"/>
            <img src="img/1.jpg" alt="1"/>
        </div>
        <div id="pointsDiv">
            <span index="1" class="on"></span>
            <span index="2"></span>
            <span index="3"></span>
            <span index="4"></span>
            <span index="5"></span>
        </div>
        <a href="javascript:;" id="prev" class="arrow"><</a>
        <a href="javascript:;" id="next" class="arrow">></a>
    </div>
    Copy the code

    JQuery code

    /** * animation **@param * element element@param StyleName styleName *@param TargetValue targetValue *@param TargetDuration targetDuration *@param The frameCount frames * /
    function moveAnimation(element, styleName, targetValue, targetDuration, frameCount, callback) {
        var $element = $(element);
        / / initial value
        var initValue = parseFloat($element.css(styleName));
        / / increment value
        var incrementValue = parseFloat(targetValue) - parseFloat(initValue);
        / / frame vectors
        var frameValue = parseFloat(incrementValue) / parseFloat(frameCount); // test:30
        / / frame length
        var frameTime = parseFloat(targetDuration) / parseFloat(frameCount); // test:10
        // Start the timer
        clearInterval($element.frameTimer);
        $element.frameTimer = setInterval(function () {
            // Calculate the process value
            var processValue = parseFloat($element.css(styleName)) + frameValue;
            $element.css(styleName, processValue);
            // Reach the target value
            if ((frameValue > 0 && processValue >= targetValue) ||
                (frameValue < 0 && processValue <= targetValue)) {
                // Stop the timer
                clearInterval($element.frameTimer);
                // Modify the target value
                $element.css(styleName, targetValue);
                // The callback function
                callback && callback();
            }
        }, frameTime);
    }
    
    /** * left offset animation *@param element
     * @param targetValue
     * @param callback* /
    function leftAnimation(element, targetValue, callback) {
        moveAnimation(element, 'left', targetValue, 200.20, callback);
    }
    
    // 1. Click the icon to the right (left) to smoothly switch to the next (upper) page
    // 2. Infinite loop switch: the previous page of the first page is the last page, and the next page of the last page is the first page
    // 3. Slide to the next page every 3s
    // 4. When the mouse enters the image area, the automatic switching stops. When the mouse leaves, the automatic switching starts again
    // 5. When switching pages, the dots below are updated simultaneously
    // 6. Click the dot icon to switch to the corresponding page
    var $container = $('#container');
    var $list = $('#list');
    var $pointsDiv = $('#pointsDiv > span');
    var $prev = $('#prev');
    var $next = $('#next');
    var lastIndex = 1;
    
    /** * Switch the image *@param targetIndex* /
    function switchPic(targetIndex) {
        // Prevent is not a number
        targetIndex = parseInt(targetIndex);
        // Prevent problems by clicking too fast
        if (targetIndex < 0 || targetIndex > 6) {
            return;
        }
        // Toggle images
        leftAnimation($list, getTargetPosition(targetIndex), function () {
            // The 0th slide is actually the 5th slide
            if (targetIndex <= 0) {
                targetIndex = 5;
                $list.css('left', getTargetPosition(targetIndex));
            }
            // The 6th slide is actually the 1st slide
            if (targetIndex >= 6) {
                targetIndex = 1;
                $list.css('left', getTargetPosition(targetIndex));
            }
            // Dot synchronizes updates
            $pointsDiv.filter('[index=' + lastIndex + '] ').removeClass('on');
            $pointsDiv.filter('[index=' + targetIndex + '] ').addClass('on');
            lastIndex = targetIndex;
        });
    
        /** * target bit **@param targetIndex
         * @returns {number}* /
        function getTargetPosition(targetIndex) {
            var picWidth = $container.css('width');
            return -targetIndex * parseFloat(picWidth); }}// automatically cut the map
    autoPic();
    var timer;
    
    function autoPic() {
        clearInterval(timer);
        timer = setInterval(function () {
            switchPic(lastIndex + 1);
        }, 3000);
    }
    
    // Hover switch
    $container.hover(function () {
        clearInterval(timer);
    }, function () {
        autoPic();
    });
    
    // Cut the origin
    $pointsDiv.on('click'.function () {
        clearInterval(timer);
        switchPic(this.getAttribute('index'));
    });
    
    // Cut a picture
    $prev.on('click'.function () {
        clearInterval(timer);
        switchPic(lastIndex - 1);
    });
    // Cut the graph
    $next.on('click'.function () {
        clearInterval(timer);
        switchPic(lastIndex + 1);
    });
    Copy the code

    The effect

    4, animation,

    animation describe
    basic show() Displays hidden matching elements
    hide() Hide displayed elements
    toggle() Used to bind two or more event handler functions in response to a rotating click event for the selected element
    sliding slideDown() Display all matched elements dynamically by height variation (increasing down), optionally firing a callback function when the display is complete
    slideUp() Hide all matched elements dynamically by varying height (decreasing upward), optionally firing a callback function when hiding is complete
    slideToggle() Toggle the visibility of all matched elements with height changes and optionally trigger a callback function when the toggle is complete
    The fading fadeIn() Fade in all matched elements by changing their opacity, optionally triggering a callback function when the animation is complete
    fadeOut() Fade out all matched elements by changing their opacity, optionally triggering a callback function when the animation is complete
    fadeTo() Increments the opacity of all matched elements to the specified opacity, optionally triggering a callback function after the animation is complete
    fadeToggle() Switches on and off all matched elements by changing their opacity and optionally triggers a callback function when the animation is complete
    The custom animate() A function for creating custom animations
    stop() Stops all animations running on the specified element
    finish() Stop currently running animations, remove all queued animations, and complete all animations matching elements
    delay() Set a delay to delay the execution of subsequent items in the queue

    FadeIn, fadeOut, fadeToggle

    Fade in and fade out: This is done by constantly changing the opacity of the element

    • fadeIn(): Drive the display of the painting
    • fadeOut(): Drive the painting to hide
    • fadeToggle(): Drive the picture to show/hide
    var $div1 = $('.div1');
    // 1. Click btn1 and slowly fade out
    / / * no arguments
    // $('#btn1').click(function () {
    // $div1.fadeOut();
    // });
    / / * have ginseng
    // * Character argument
    // * Digital arguments
    // $('#btn1').click(function () {
    // $div1.fadeOut('slow');
    // });
    $('#btn1').click(function () {
        $div1.fadeOut(1000);
    });
    // 2. Click btn2 and slowly fade in
    $('#btn2').click(function () {
        $div1.fadeIn('slow');
    });
    // 3. Click btn3, fade out/fade in toggle, animation end prompt "animation end"
    $('#btn3').click(function () {
        $div1.fadeToggle('slow'.'linear'.function () {
            alert('End of animation');
        });
    });
    Copy the code

    SlideUp, slideDown, slideToggle

    Sliding animation: Constantly changing the height of an element is implemented

    • slideDown(): Drives the development of the painting
    • slideUp(): Drive the contraction of the painting
    • slideToggle(): Drives the switching expansion/contraction of the painting
    var $div1 = $('.div1');
    // 1. Click btn1 and swipe up
    $('#btn1').click(function () {
        $div1.slideUp(1000);
    });
    // 2. Click btn3 and swipe down
    $('#btn2').click(function () {
        $div1.slideDown('slow');
    });
    // 3. Click btn3 to switch up/down
    $('#btn3').click(function () {
        $div1.slideToggle('slow'.'linear'.function () {
            alert('End of animation');
        });
    });
    Copy the code

    Show, hide, toggle

    Display hidden, no animation by default, animation (opacity/height/width)

    • show()(not) drive the display of the painting
    • hide()(no) drive the hiding of the painting
    • toggle()(no) drive the painting to switch display/hide
    var $div1 = $('.div1');
    // 1. Click btn1 to display immediately
    $('#btn1').click(function () {
        $div1.show();
    });
    // 2. Click btn2 to slowly display
    $('#btn2').click(function () {
        $div1.show('slow');
    });
    // 3. Click btn3 and slowly hide
    $('#btn3').click(function () {
        $div1.hide('slow');
    });
    // 4. Click btn4 to switch show/Hide
    $('#btn4').click(function () {
        $div1.toggle();
    });
    Copy the code

    Exercise: navigation bar dynamic display effect

    The HTML code

    <div id="navigation">
        <ul>
            <li><a href="#">Home page</a></li>
            <li>
                <a href="#">shirt</a>
                <ul>
                    <li><a href="#">Short sleeve shirt</a></li>
                    <li><a href="#">Long sleeve shirt</a></li>
                    <li><a href="#">Sleeveless shirt</a></li>
                </ul>
            </li>
            <li>
                <a href="#">fleece</a>
                <ul>
                    <li><a href="#">Cardigan fleece</a></li>
                    <li><a href="#">Set head fleece</a></li>
                </ul>
            </li>
            <li>
                <a href="#">The trousers</a>
                <ul>
                    <li><a href="#">Casual pants</a></li>
                    <li><a href="#">Khaki pants</a></li>
                    <li><a href="#">A pair of jeans</a></li>
                    <li><a href="#">shorts</a></li>
                </ul>
            </li>
            <li><a href="#">Contact us</a></li>
        </ul>
    </div>
    Copy the code

    JQuery code

    var $navigation = $('#navigation >ul>li:has(ul)');
    $navigation.hover(function () {$(this).children('ul').stop().slideDown();
    }, function () {$(this).children('ul').stop().slideUp();
    });
    Copy the code

    The effect

    5. Coexistence of multiple libraries

    Problem: If two libraries have $, there is a conflict

    $($); $($); $($); $($)

    API: jQuery. Of noconflict ()

    // Release the use of clothes
    jQuery.noConflict();
    // Call s in myLibThe $();// If you want to use jQuery, you can only use jQuery
    jQuery(function () {
        console.log('Document load completed');
    });
    console.log('+ + + + +');
    Copy the code

    6. Onload and Ready

    $(document).ready()

    window.onload

    • Images including the page will be called back after loading (late)
    • There can be only one listening callback

    $(document).ready()

    • Is equal to:$(function(){})
    • Callback as soon as the page loads (early)
    • You can have multiple listening callbacks
    // 1. Print the width of img and observe its value
    console.log('direct', $('#logo').width()); / / 0 directly
    
    // 2. Print the width of img in $(function(){})
    $(function () {
        console.log('ready', $('#logo').width()); // ready 0
    });
    
    // 3. Print the width of img in window.onload
    window.onload = function () {
        console.log('onload', $('#logo').width()); // onload 190
    };
    
    // 4. Print the width after img is loaded
    $('#logo').on('load'.function () {
        console.log('img load', $('#logo').width()); // img load 190
    });
    Copy the code