This is the 8th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Life is short. Let’s learn Python

Introduction to jQuery Functions

JQuery encapsulates native JS code internally, but also adds a lot of functionality. JQuery can complete JS operations by writing less code, and is compatible with multiple browsers at the same time, so there is no need to consider browser compatibility when using jQuery

JQuery File download

JQuery official website open, click download, select compressed version or uncompressed version

Copy and paste it into a text file, change the suffix to.js, and place the file in a folder in your project

The introduction of the jQuery

Methods a

The downloaded JS file can be placed under the project file

<script src="jQuery.js">
Copy the code

Way 2

JQuery provides the CDN service (based on network direct request loading), the front-end free CDN website: BOOTCDN

< script SRC = "https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js" > < / script > "" "your computer must have a network "" "Copy the code

JQuery Basic Syntax

The basic grammar

$jQuery() === $() $() === $()Copy the code

JQuery vs. JS code

  • Change the text color inside the p tag to red
// js native code
let pEle = document.getElementById('p1');
pEle.style.color = 'red';

/ / jQuery code
$('p').css('color'.'blue')
Copy the code

The jQuery lookup tag selector

Basic selector

The id selector

$('#d1');
jQuery.fn.init [p#d1]
Copy the code

The class selector

$('.c1');
jQuery.fn.init [div#d2.c1, prevObject: jQuery.fn.init(1)]
Copy the code

Label selector

$('span');
jQuery.fn.init [span#d3, prevObject: jQuery.fn.init(1)]
Copy the code

Focus on knowledge

// The array generated by the selector is a jQuery object

// How does a jQuery object become a tag object
$('#d1') [0];
<p id="d1">​p​</p>document.getElementById('d1');
<p id="d1">​p​</p>// How to convert jQuery objects to tag objects
$(document.getElementById('d1'));
jQuery.fn.init [p#d1]
Copy the code

Combine selectors/groups with nesting

$('div')
w.fn.init(2) [div#d1, div.c1, prevObject: w.fn.init(1The $()]'div.c1')
w.fn.init [div.c1, prevObject: w.fn.init(1)]0: div.c1length: 1prevObject: w.fn.init [document]__proto__: Object(0The $()'div#d1')
w.fn.init [div#d1, prevObject: w.fn.init(1The $()]The '*')
w.fn.init(19) [html, head, meta, title, meta, link, script, script, body, span, span, div#d1, span, p#d2, span, span, div.c1, span, span, prevObject: w.fn.init(1The $()]'#d1,.c1,p') # juxtaposing + mixing3) [div#d1, p#d2, div.c1, prevObject: w.fn.init(1The $()]'div span') # offspring W.F. Init (3) [span, span, span, prevObject: w.fn.init(1The $()]'div>span') # son w.f. n. I nit(2) [span, span, prevObject: w.fn.init(1The $()]'div+span'[span,prevObject: w.fn.init(1The $()]'div~span') # Brother W.F. Init (2) [span, span, prevObject: w.fn.init(1)]
Copy the code

Basic filter

Secondary screening of the results already obtained

$('ul li')
w.fn.init(10) [li, li, li, li, li, li, li.c1, li, li#d1, li, prevObject: w.fn.init(1The $()]'ul li:first') # eldest son w.f. init [li,prevObject: w.fn.init(1)]0: lilength: 1prevObject: w.fn.init [document]__proto__: Object(0The $()'ul li:last') # The youngest son W.f.prevObject: w.fn.init(1)]0: lilength: 1prevObject: w.fn.init [document]__proto__: Object(0The $()'ul li:eq(2)'[li] [li] [li]prevObject: w.fn.init(1)]0: lilength: 1prevObject: w.fn.init [document]__proto__: Object(0The $()'ul li:even') # even index0Included in w.F. Init (5) [li, li, li, li.c1, li#d1, prevObject: w.fn.init(1)]0: li1: li2: li3: li.c14: li#d1length: 5prevObject: w.fn.init [document]__proto__: Object(0The $()'ul li:odd') # odd-numbered index5) [li, li, li, li, li, prevObject: w.fn.init(1)]0: li1: li2: li3: li4: lilength: 5prevObject: w.fn.init [document]__proto__: Object(0The $()'ul li:gt(2)') # greater than index w.f. init(7) [li, li, li, li.c1, li, li#d1, li, prevObject: w.fn.init(1)]0: li1: li2: li3: li.c14: li5: li#d16: lilength: 7prevObject: w.fn.init [document]__proto__: Object(0The $()'ul li:lt(2)') # < index w.f. init(2) [li, li, prevObject: w.fn.init(1)]0: li1: lilength: 2prevObject: w.fn.init [document]__proto__: Object(0The $()'ul li:not("#d1")'# Remove labels that meet the criteria9) [li, li, li, li, li, li, li.c1, li, li, prevObject: w.fn.init(1The $()]'div')
w.fn.init(2) [div, div, prevObject: w.fn.init(1The $()]'div:has("p")') # select a tag that contains one or more tagsprevObject: w.fn.init(1)]
Copy the code

Property selector

$('[username]')
w.fn.init(3) [input, input, p, prevObject: w.fn.init(1The $()]'[username="jason"]')
w.fn.init [input, prevObject: w.fn.init(1The $()]'p[username="egon"]')
w.fn.init [p, prevObject: w.fn.init(1The $()]'[type]')
w.fn.init(2) [input, input, prevObject: w.fn.init(1The $()]'[type="text"]')
w.fn.init(2) [input, input, prevObject: w.fn.init(1)]
Copy the code

Form filters – for form forms

$('input[type="text"]')
w.fn.init [input, prevObject: w.fn.init(1)]0: inputlength: 1prevObject: w.fn.init [document]__proto__: Object(0The $()'input[type="password"]')
w.fn.init [input, prevObject: w.fn.init(1The $()]':text'W. f. init [input,prevObject: w.fn.init(1)]0: inputlength: 1prevObject: w.fn.init [document]__proto__: Object(0The $()':password'W. f. init [input,prevObject: w.fn.init(1)] :text :password :file :radio :checkbox :submit :reset :button ... Properties of the form object: Enabled :disabled :checked: Selected"""Special circumstances"""
$(':checked'# It will take both checked and selected2) [input, option, prevObject: w.fn.init(1)]0: input1: optionlength: 2prevObject: w.fn.init [document]__proto__: Object(0The $()':selected') # It won't just take selected w.f. init [option,prevObject: w.fn.init(1The $()]'input:checked'# add a constraint on yourself.prevObject: w.fn.init(1)]
Copy the code

Filter method

$('#d1').next() # w.f. init [span,prevObject: w.fn.init(1)]0: spanlength: 1prevObject: w.fn.init [span#d1]__proto__: Object(0The $()'#d1').nextall () #5) [span, div#d2, span, span, span.c1, prevObject: w.fn.init(1)]0: span1: div#d22: span3: span4: span.c1length: 5prevObject: w.fn.init [span#d1]__proto__: Object(0The $()'#d1').nextUntil('.c1') # does not include the last w.F. init(4) [span, div#d2, span, span, prevObject: w.fn.init(1)]0: span1: div#d22: span3: spanlength: 4prevObject: w.fn.init [span#d1]__proto__: Object(0The $()'.c1').prev() #prevObject: w.fn.init(1)]0: spanlength: 1prevObject: w.fn.init [span.c1, prevObject: w.fn.init(1)]__proto__: Object(0The $()'.c1').prevall () # above all w.F. init(5) [span, span, div#d2, span, span#d1, prevObject: w.fn.init(1The $()]'.c1').prevUntil('#d2') # until the tag with id d2 does not include the tag with ID D2 w.f. init(2) [span, span, prevObject: w.fn.init(1The $()]'#d3').parent() # # parent tag w.f. init [p,prevObject: w.fn.init(1)]0: plength: 1prevObject: w.fn.init [span#d3]__proto__: Object(0The $()'#d3').parent().parent()
w.fn.init [div#d2, prevObject: w.fn.init(1The $()]'#d3').parent().parent().parent()
w.fn.init [body, prevObject: w.fn.init(1The $()]'#d3').parent().parent().parent().parent()
w.fn.init [html, prevObject: w.fn.init(1The $()]'#d3').parent().parent().parent().parent().parent()
w.fn.init [document.prevObject: w.fn.init(1The $()]'#d3').parent().parent().parent().parent().parent().parent()
w.fn.init [prevObject: w.fn.init(1The $()]'#d3').parents() # Get a parent tag for each level4) [p, div#d2, body, html, prevObject: w.fn.init(1The $()]'#d3').parentsUntil('body')
w.fn.init(2) [p, div#d2, prevObject: w.fn.init(1The $()]'#d2').children() # son $('#d2'# siblings($)'div p'# equivalent $('div').find('p') # find filters the desired tags from a certain area"""Optimize the basic filter"""
$('div span:first')
w.fn.init [span, prevObject: w.fn.init(1The $()]'div span').first()
w.fn.init [span, prevObject: w.fn.init(3)]0: spanlength: 1prevObject: w.fn.init(3) [span, span#d3, span, prevObject: w.fn.init(1)]__proto__: Object(0The $()'div span:last')
w.fn.init [span, prevObject: w.fn.init(1The $()]'div span').last()
                                                                                    
w.fn.init [span, prevObject: w.fn.init(3The $()]'div span:not("#d3")')
w.fn.init(2) [span, span, prevObject: w.fn.init(1The $()]'div span').not('#d3')
w.fn.init(2) [span, span, prevObject: w.fn.init(3)]
Copy the code

JQuery Operation Tag

Action class

Js native code versus jQuery

Js native code JQuery version
Add class classList.add() addClass()
Delete the class classList.remove() removeClass(
Determine whether to include a class classList.contains() hasClass()
Toggle method classList.toggle() toggleClass()

Manipulation of label styles (CSS)

<p>111</p>
<p>222</p>
// Requirement: one line of code makes the first p tag red and the second green
$('p').first().css('color'.'red').next().css('color'.'green');
/* You can use jQuery to do a single line of code to do many tags */
Copy the code

Position operation — scrollTop

// The current position from the top of the browser window
$(window).scrollTop();

// Set the page distance from the top of the window
$(window).scrollTop(300);
Copy the code

Label size

// Code preparation
<p>p</p>

// The height of the text
$('p').height();
20.8
// The width of the text itself
$('p').width();
490.4 

/ / text + padding
$('p').innerHeight();
$('p').innerWidth();

/ / text + padding + border
$('p').outerHeight();
$('p').outerWidth();

Copy the code

Manipulate the text inside the label

Js native code versus jQuery

Js native code jquery
innerText text()
innerHTML html()

JQuery manipulates text within a tag

// View all text within the label
$('div').text();
// View the text inside the tag, including the tag
$('div').html();

// Modify the internal text of the label
$('div').text('Today is 520');
$('div').html('Today is 520');
$('div').text('<h1>520</h1>');
$('div').html('<h1>520</h1>');
Copy the code

Gets the value entered by the user

Js native code versus jQuery

Js native code jquery
.value .val()

JQuery gets value operations

// Get the data entered by the user in the input box
$('#d1').val();
// Set the data displayed in the input box
$('#d1').val('520 (´ del ` ʃ ♡ ƪ)');

// Obtain the file uploaded by the user
$('#d2').val()  // Obtain the file path
$('#d2') [0].files[0]  // Convert the jQuery object to a tag object
Copy the code

Operation Tag Attribute

Js native code versus jQuery

Js native code jquery
Set properties setAttribute() attr(name,value)
Get properties getAttribute() attr(name)
Delete the properties removeAttribute() removeAttr(name)
  • Supplement knowledge
$XXXEle jQuery = $XXXEle jQuery = $XXXEle jQuery = $XXXEleCopy the code

JQuery operates on the attributes of tags

  • There are properties and custom properties that can be seen on the tag
// Get the jQuery object
let $pELe = $('p');
// Get the id of the object
$pEle.attr('id');
// Get the class of the object
$pEle.attr('class');
// Set properties for the object
$pEle.attr('class'.'c1');
// Remove an attribute
$pEle.removeAttr('class')
Copy the code
  • Use prop to return a Boolean value, such as whether checkbox radio option is selected
$('#d3').attr('checked')
"checked"
$('#d2').attr('checked')
undefined
$('#d2').attr('checked')
undefined
$('#d4').attr('checked')
undefined
$('#d3').attr('checked')
"checked"
$('#d3').attr('checked'.'checked'# # # # # # # # # # #'#d2').prop('checked')
false
$('#d2').prop('checked')
true
$('#d3').prop('checked'.true)
w.fn.init [input#d3]
$('#d3').prop('checked'.false)
w.fn.init [input#d3]
Copy the code

JQuery manipulates HTML documents

Js native code versus jQuery

Js native code jquery
createElement(‘p’) $(‘

‘)

appendchild() append()

JQuery manipulates HTML documents

// Create a label
let $pEle = $('<p>');
// Add text to the label
$pEle.text('Today is 520');// Add attributes to the tag
$pEle.attr('id'.'d1');


// Specifies which TAB to append to
$('#d2').append($pEle);
or
$pEle.appendto($('#d2'));

// Specify which TAB to append at the forehead
$('#d2').prepend($pEle);
or
$pEle.prependto($('#d2'));

// Put it after a tag
$('#d2').after($pEle);
or
$pEle.insertAfter($('#d2'))

// Put in front of a tag
$('#d2').before($pEle);
or
$pEle.insertBefore($('#d2'))


// Remove the tag from the DOM tree
$('#d2').remove()

// Clear all contents of the tag
$('#d2').empty();
Copy the code

JQuery event

How to bind an event to a label

The first kind of

// jQuery object. Events (functions that trigger event implementations)
$('#d1').click(function(){
    alter('How old are you?')})Copy the code

The second,

// More powerful, support event delegate
// jQuery object. On (' event ', triggers the event implementation function)
$('#d1').on('click'.function(){
    alert('Forget how old I am')})Copy the code

Cloning of events

  • Effect: click on the label to make a copy of exactly the same on the page
    <style>
        #d1 {
            height: 50px;
            width: 50px;
            background: hotpink;
            border: 3px solid black;
        }
    </style>
</head>
<body>
    <button id="d1">click</button>
    <script>

        $('#d1').on('click'.function () {
            console.log(this);  // this refers to the tag object being operated on
            // Clone by default, only HTML and CSS events are cloned
            $(this).clone(true).insertAfter($('body'))})</script>
</body>
Copy the code

The left side menu

  • To achieve the effect, three menus, click on a menu to show the menu under the directory, the other two menu of the directory hidden
 <style>
        body.html {
            margin: 0;
            height: 100%;
            width: 100%;
        }
       #v1 {
           float: left;
           height: 100%;
           width: 30%;
           background: # 888888;
           text-align: center;
           color: #eeeeee;
           font-size: 20px;
       }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
    <div id="v1">
        <div class="menu" id="d1">A menu<p class="title">1</p>
            <p class="title">2</p>
            <p class="title">3</p>
        </div>
        <div class="menu" id="d2">The menu 2<p class="title">4</p>
            <p class="title">5</p>
            <p class="title">6</p>
        </div>
        <div class="menu" id="d3">Menu 3<p class="title">1</p>
            <p class="title">2</p>
            <p class="title">3</p>
        </div>
    </div>

    <script>
        $('.menu').click(function () {
            // Make all menu headings have the hide attribute
            $('.title').addClass('hide');
            // Click on the menu to delete the hide property of the title under that menu
            $(this).children().removeClass('hide')})</script>
Copy the code

Return to the top

  • Effect: When the window on the page is some distance from the top of the browser, the display goes back to the top
    <style>
        body.html {
            margin: 0;
            height: 100%;
            width: 100%;
        }
        #d1 {
            background: #4e4e4e;
            height: 800px;
            width: 100%;
        }
        #d2 {
            background: # 888888;
            height: 800px;
            width: 100%;
        }
        #d3 {
            background: # 333333;
            height: 800px;
            width: 100%;
        }
        #d4 {

            position: fixed;
            right: 20px;
            bottom: 20px;
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
    <a href="" id="'d1"></a>
    <div id="d1">

    </div>
    <div id="d2">

    </div>
    <div id="d3">

    </div>
    <a href="" class="hide" id="d4">Back to the top</a>


    <script>
        $(window).scroll(function () {
            if ($(window).scrollTop() <= 300) {$('#d4').addClass('hide')}else{$('#d4').removeClass('hide')}})</script>
</body>
Copy the code

Custom login verification

  • Effect: when obtaining the user name and password, if the user does not fill in the information, the user should be prompted
<p>username:
    <input type="text" id="username">
    <span style="color: red"></span>
</p>
<p>password:
    <input type="text" id="password">
    <span style="color: red"></span>
</p>
<button id="d1">submit</button>

<script>
    let $userName = $('#username')
    let $passWord = $('#password'The $()'#d1').click(function () {
        // Obtain the user name and password entered by the user for verification
        let userName = $userName.val()
        let passWord = $passWord.val()
        if(! userName){ $userName.next().text("Username cannot be empty.")}if(! passWord){ $passWord.next().text('Password cannot be empty'The $()}})'input').focus(function () {$(this).next().text(' ')})</script>
Copy the code

Input Real-time monitoring

  • Implementation: What does the back end receive when the user enters it
<input type="text" id="d1">

<script>
    $('#d1').on('input'.function () {
        console.log(this.value)  
    })
</script>
Copy the code

Hover event

  • Effect: the mouse hover on a label popover effect, remove popover effect
<script>
    $("#d1").hover() {$("#d1").hover()
    // alert(123)
    // })

    $('#d1').hover(
        function () {
            alert('HERE I come')  / / suspended
    },
        function () {
            alert('I slipped away')  / / removed})</script>
Copy the code

Keyboard key press event

  • Effect: press a key on the keyboard, the back end can receive which is pressed
<script>
    $(window).keydown(function (event) {
        console.log(event.keyCode)
        if (event.keyCode === 16){
            alert('You hit shift.')
        }
    })
</script>
Copy the code

Modal dialog

Prevents the execution of subsequent events

  • The effect is to prevent the refresh of the form submission
<form action="">
    <span id="d2"></span>
    <input type="submit" id="d1" value="click me">
    <script>
        $('#d1').click(function () {$('#d2').text('Just ate porridge with preserved eggs')
            // Block the execution of subsequent events of the tag
            return false
            // Block the execution mode 2 of the tag subsequent events
        // e.preventDefault()
        })
    </script>
</form>
Copy the code

Prevent bubbling events

  • When the tags nested inside the parent tag have the same functions as the parent tag, the events on the child tag are triggered, and the events on the parent tag are also triggered. This is to prevent this phenomenon from happening
<body>
    <div id="d3">div
        <p id="d2">div>p
            <span id="d1">div>p>span</span>
        </p>
    </div>
    <script>

        $('#d1').click(function () {
            alert('span')}); $('#d2').click(function () {
            alert('p')}); $('#d3').click(function (e) {
            alert('div')
            // Stop event bubbling in way 1
            // return false
            // Stop event bubbling in way 2
            // e.stopPropagation()
        })
</script>


</body>
Copy the code

Event delegation

  • Effect: Bind click events to all button labels on the page
<button> Is a brother, come to cut me!! </button><script>
    // Bind the click event to all button labels on the page
    $('button').click(function () {// cannot affect dynamically created tags
    // alert(123)
    // })

    // Event delegate
    $('body').on('click'.'button'.function () {
        alert(123)  // Delegate events to a tag within the specified scope, whether the tag is written beforehand or dynamically created later
    })
</script>
Copy the code

Page load

Wait for the page to load before executing the codewindow.onload = function(){
  / / js code
}

"""Wait for the page to load in jQuery"""$($($))document).ready(function(){
  / / js code}) # $($()function(){
  / / js code}) # Third"""Write directly at the bottom of the body."""
Copy the code

Animation effects

Hide hide/ show show

    <style>
        body.html {
            height: 100%;
            width:100%;
        }
        #d3  {
            height: 100%;
            width: 30%;
            background: # 888888;
            border: 3px solid red;
        }
        #d1.#d2 {
            display: block;
            float: left;
        }

    </style>
</head>
<body>
    <div id="d3">div</div>
    <button id="d1">hidden</button>
    <button id="d2">According to</button>
    <script >
        $('#d1').on('click'.function () {$('#d3').hide(5000)}); $('#d2').click(function () {$('#d3').show(5000)})</script>
</body>
Copy the code

Slide down and up

<style>
        body.html {
            height: 100%;
            width:100%;
        }
        #d3  {
            height: 100%;
            width: 30%;
            background: # 888888;
            border: 3px solid red;
        }
        #d1.#d2 {
            display: block;
            float: left;
        }

    </style>
</head>
<body>
    <div id="d3">div</div>
    <button id="d1">hidden</button>
    <button id="d2">According to</button>
    <script >
        $('#d1').on('click'.function () {$('#d3').slideUp(5000)}); $('#d2').click(function () {$('#d3').slideDown(5000)})</script>
</body>
Copy the code

The gradient

 <style>
        body,html {
            height: 100%;
            width:100%;
        }
        #d3  {
            height: 100%;
            width: 30%;
            background: #888888;
            border: 3px solid red;
        }
        #d1,#d2 {
            display: block;
            float: left;
        }

    </style>
</head>
<body>
    <div id="d3">div</div>
    <button id="d1">hidden</button>
    <button id="d2">According to</button>
    <button id="d4">The gradient to</button>

    <script >
        $('#d1').on('click'.function () {$('#d3').fadeIn(5000)}); $('#d2').click(function () {$('#d3').fadeOut(5000)}); $('#d4').click(function () {$('#d3').fadeTo(5000.0.5)})</script>
</body>
Copy the code

each()

describe

JQuery. Each (collection, callback (indexInArray valueOfElement)) :

Description: a generic iteration function that can be used to seamlessly iterate over objects and arrays. Arrays and array-like objects iterate over a numeric index, from 0 to length-1, through a length property, such as a function’s argument object. Other objects iterate over their property names.

Iterative array

li =[10.20.30.40]
$.each(li,function(i, v){
  console.log(i, v);//index is the index, ele is the specific element of each loop.
})

// Run result
010
120
230
340
Copy the code

Iterating jQuery Objects

.each (function (index, Element)) :

Description: Iterates through a jQuery object, executing a function for each matching element.

The.each() method iterates over each DOM element in the jQuery object. Each time the callback function executes, it passes the current number of loops as an argument (counting from 0). Because the callback is fired in the context where the current DOM element is the context, the keyword this always refers to that element.

// Add foo for each li tag
$("li").each(function(){$(this).addClass("c1");
});
Copy the code

Note: the jQuery method returns a jQuery object that iterates over the elements in the jQuery collection – a process known as implicit iteration. When this happens, it usually doesn’t need to explicitly loop the.each() method:

In other words, there is no need to use each() in the example above. Instead, write something like this:

$("li").addClass("c1");  // Perform uniform operations on all labels
Copy the code

Terminate the each loop

You can use return false to end the each loop early during the traversal

return false;Copy the code

data()

describe

The value of a data store that stores any relevant data on all elements in the matched set of elements or returns the given name of the first element in the matched set of elements.

.data(key, value):

Description: Stores any related data on matched elements.

$("div").data("k".100);// Save a value of 100 for all div tags named k
Copy the code

.data(key):

Description: Returns the data store value of a given name for the first element in a set of matching elements – set by the.data(name, value) or HTML5 data-* attribute.

$("div").data("k");// Return the value of "k" stored in the first div tag
Copy the code

.removeData(key):

Description: Remove data stored on an element. If the key parameter is not added, all saved data is removed

$("div").removeData("k");  // Remove the data corresponding to k from the element
Copy the code

conclusion

The article was first published in the wechat official account program Yuan Xiaozhuang, and was synchronously published in Digijin and Zhihu.

Please explain where it came from. If you pass by, please put out your cute little finger and click like before you go (╹▽╹)