jQuery learning notes

1. Introduction to jQuery

JavaScript+Query (query), which is a js class library to assist JavaScript development. Its core idea is write less, do more, so it realizes many browser compatibility problems.

jQuery is free and open source. Its syntax design can make development more convenient, such as operating document objects, selecting DOM elements, making animation effects, event processing, using Ajax and other functions

2. jQuery core function$

js native click event

        window.onload = function() {
            var btnObj = document.getElementById("btnId");
            alert(btnObj);
            btnObj.onclick = function() {
                alert("js Native click event");
            }
        }

Click event for jQuery

$(function(){   //Equivalent to window onload = function(){ }
    var btnId = $("#btnId");   
    btnId.click(function (){
        alert("jQuery Click event for");
    })
});

The $() function will perform different functions according to the parameters it passes in

  1. When the input parameter is [function]:

    Indicates the operation after the page is loaded, which is equivalent to window onload = function(){ }

  2. When the input parameter is [HTML string]:

    Create the element node dom object from this string

    $("<div><span>span1</span><span>span2</span></div>").appendTo("body");
    
  3. When the input parameter is [selector string]:

    Find the element node object based on this string

  4. When the input parameter is a [DOM] object:

    Wrapping DOM objects as jQuery objects returns

3. jQuery object

Essence of jQuery object: array of dom objects + a series of function functions provided by jquery

DOM object and jQuery object are converted to each other:

  1. DOM object to jQuery object
    1. Get the DOM object first
    2. $(DOM object) returns the jQuery object
  2. Convert jQuery object to DOM object
    1. Get the jQuery object first
    2. jQuery object [subscript] retrieves the corresponding DOM object

4. jQuery selector

4.1 foundation selector

  • $("#id"): find label object by ID
  • $(". class"): according to class to find label objects
  • $("tagName"): find tag objects according to tag names, such as div and span
  • $("*"): select all elements
  • $("selector1, selector2,..."): combine selectors, merge the results of multiple selectors and return

4.2 level selector

  • ("descendant of ancestor element"):
  • $("parent > child"): child element under parent element
  • $("prev + next"): matches all elements immediately after the prev element
  • $("prev ~ siblings"): matches all sibling elements after prev elements

4.3 filter selector

Basic filter selector

  • $("selector**: first * *"): get the first matching element
  • $("selector: last"): get the last matching element
  • $("selector: not (selector)"): removes all elements that match a given selector
  • $("selector: even"): matches all elements with even index value, counting from 0
  • $("selector: odd"): matches all elements with odd index values, counting from 0
  • $("selector: EQ (index)"): an element that matches a given index value
  • $("selector: GT (index)"): matches all elements greater than the given index value
  • $("selector: LT (index)"): matches all elements less than the given index value
  • $("selector: header"): matches all header elements such as h1, h2 and h3
  • $("selector: animated"): matches all elements that are performing animation

Filter content selector

  • $("selector: contains (text)"): matches the element containing the given text
  • $("selector: empty"): matches all empty elements that do not contain child elements or text
  • $("selector: parent"): matches elements that contain child elements or text
  • $("selector: has (selector)"): matches the element that contains the element that the selector matches

Attribute filter selector

  • $("selector [attribute]"): matches the element containing the given attribute
  • $("selector [attribute = value]"): the element matching a given attribute is a specific value
  • $("selector [attribute! = value]"): matches elements that do not contain a given attribute or that are not equal to a specific value
  • $("selector [attribute ^ = value]"): matching a given attribute is an element that starts with some value
  • $("selector [attribute $= value]"): the element that matches the given attribute is one that ends with some value
  • $("selector [attribute * = value]"): matching a given attribute is an element that contains some values

practice:

$("div[title]")
$("div[title='test']")
$("div[title!='test']")
$("div[title^='te']")
$("div[title$='est']")
$("div[title*='es']")
$("div[id][title*='es']")
$("div[title][title!='test']")

Form filter selector

: input

: text

: password

: radio

: checkbox

: submit

: reset

: button

: file

: hidden

: checked

: selected

$(":enabled :text").val("xxxx");

**val() * * you can get and set the value attribute value of the form item

$(":checkbox:checked").each(function (){
	console.log(this.value);
})

**each (function () {}) * * method is a method provided by jQuery object to traverse elements. In the traversed function function, there is a this object, which is the dom object currently traversed

4.4 element screening

exp is the selector

  • eq (): gets the element of the given index
  • First (): get the first element
  • Last (): get the last element
  • filter (exp): leave matching elements
  • Is (): judge whether the given selector matches. As long as there is a match, it returns true
  • has (exp): returns the element containing the element matching the selector
  • not (exp): deletes the element that matches the selector
  • children (exp): returns the child element that matches the given selector
  • find (exp): returns the descendant element that matches the given selector
  • Next (): returns the next sibling element of the current element
  • nextAll (exp): returns all sibling elements behind the current element
  • nextUntil(): returns the following elements from the current element to the specified matching element
  • Parent (): returns the parent element
  • prev (exp): returns the previous sibling element of the current element
  • Prevlall(): returns all sibling elements in front of the current element
  • prevUntil(): returns the previous element from the current element to the specified matching element
  • siblings (exp): returns all sibling elements

5. jQuery method

  • html (): set or get the contents in the start tag and end tag, just like the dom attribute innerHTML

  • Text(): set or get the text in the start tag and end tag, which is the same as the dom attribute innerText

  • val(): set or get the value attribute value of the form item, which is the same as the dom attribute value

  • attr(): set or get the attribute value. It is not recommended to operate checked, readOnly, selected, disabled, etc. it can also operate non-standard attributes, such as custom attribute: abc

    . attr ("name") -- get

    . attr ("name", "abc") -- setting

  • prop(): set or get the attribute value. Only recommended operations are checked, readOnly, selected, disabled, etc

Internal insertion

  • appendTo (): a.appendTo(b), insert a to the end of the B child element to become the last child element
  • prependTo(): a.prependTo(b). Find a in front of all child elements of B and become the first child element

External insertion

  • insertAfter(): a.insertAfter(b), get ba
  • Insertbefore(): a.insertBefore(b), get ab

replace

  • replaceWith(): a.replaceWith(b), replace a with B
  • replaceAll (): a.replaceAll(b), replace all B with a

delete

  • Remove(): a.remove(), delete a tag
  • Empty(): a.empty(), empty the contents of a tag

Add style

  • addClass(): add one or more classes to the selected element

  • removeClass(): Deletes one or more classes from the selected element

  • toggleClass(): switch class operations for adding / deleting selected elements

  • offset (): gets or sets the position of the element

    xxx.offset({

    ​ top:100,

    ​ left:50

    })

Exercise: choose all or none

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../script/jquery-3.5.1.js"></script>
    <script type="text/javascript">
        $(function (){
            //Select all
            $("#checkedAllBtn").click(function (){
                $(":checkbox").prop("checked",true);
            });

            //Not at all
            $("#checkedNoBtn").click(function (){
               $(":checkbox").prop("checked",false);
            });

            //Reverse selection
            $("#checkedRevBtn").click(function (){
                $(":checkbox[name='items']").each(function (){
                    this.checked = !this.checked;
                });
                var allCount = $(":checkbox[name='items']").length;
                var checkedCount = $(":checkbox[name='items']:checked").length;

                $("#checkedAllBox").prop("checked", allCount==checkedCount);

            });

        //    Submit
            $("#sendBtn").click(function (){
                list = [];
                $(":checkbox[name='items']:checked").each(function (){
                    list.push(this.value);
                });
                alert(list);
            });

        //  Select all / deselect all
        $("checkedAllBox").click(function (){
            $(":checkbox[name='items']").prop("checked",this.checked);
        });

        $(":checkbox[name='items']").click(function (){
            var allCount = $(":checkbox[name='items']").length;
            var checkedCount = $(":checkbox[name='items']:checked").length;

            $("#checkedAllBox").prop("checked", allCount==checkedCount);
        });

        })
    </script>
</head>
<body>
    <form method="post" action="">
        What's your favorite sport?<input type="checkbox" id="checkedAllBox" />Select all/Not at all
        <br />
        <input type="checkbox" name="items" value="Football" />Football
        <input type="checkbox" name="items" value="Basketball" />Basketball
        <input type="checkbox" name="items" value="badminton" />badminton
        <input type="checkbox" name="items" value="Table Tennis" />Table Tennis
        <br/>
        <input type="button" id="checkedAllBtn" value="Select all"/>
        <input type="button" id="checkedNoBtn" value="Not at all"/>
        <input type="button" id="checkedRevBtn" value="Reverse selection"/>
        <input type="button" id="sendBtn" value="Submit"/>
    </form>
</body>
</html>

Exercise: dynamically adding and deleting records

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        table{
            margin: 0 auto;
            border: 1px solid black;

        }
    </style>
    <script src="../script/jquery-3.5.1.js"></script>
    <script type="text/javascript">
        var deleteFunction = function () {
            var trObj = $(this).parent().parent();
            if(confirm("confirm deletion"+trObj.find(":first").text()+"Are you?")){
                trObj.remove();
            }
            return false;
        };
        $(function (){
            $("#addEmpButton").click(function () {
                var name = $("#empName").val();
                var email = $("#email").val();
                var salary = $("#salary").val();
                var trObj = $("<tr>" +
                    "            <td>"+name+"</td>" +
                    "            <td>"+email+"</td>" +
                    "            <td>"+salary+"</td>" +
                    "            <td><a href=\"deleteEmp?id=001\">Delete</a></td>" +
                    "        </tr>");
                trObj.appendTo($("#employeeTable"));
                trObj.find("a").click(deleteFunction)
            });
            //Bind click events to deleted a Tags
            $("a").click(deleteFunction);
        })
    </script>
</head>
<body>
    <table id="employeeTable">
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Salary</th>
            <th> </th>
        </tr>
        <tr>
            <td>Tom</td>
            <td>tom@tom.com</td>
            <td>5000</td>
            <td><a href="deleteEmp?id=001">Delete</a></td>
        </tr>
        <tr>
            <td>Jerry</td>
            <td>jerry@sohu.com</td>
            <td>8000</td>
            <td><a href="deleteEmp?id=002">Delete</a></td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>Bob@163.com</td>
            <td>10000</td>
            <td><a href="deleteEmp?id=003">Delete</a></td>
        </tr>
    </table>
    <div id="formDiv">
        <h4 align="center">Add new employee</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>
</body>
</html>

6. jQuery animation

The following methods can add parameters:

  • The first parameter is the animation execution time, in milliseconds
  • The second parameter is the callback function of the animation

Basic animation

  • show(): show hidden elements
  • Hide (): hide visible elements
  • toggle: hidden, visible

Fade in and fade out animation

  • fadeIn(): fade in (display)
  • fadeOut(): fade out (disappear)
  • fadeToggle(): fadeToggle
  • fadeTo(): change the transparency to the specified value within the specified time. 0 is transparent and 1 is fully visible

7. Events

  1. The jQuerr event is executed after the browser kernel parses the label of the page and creates a dom object
  2. The native js event is executed after the browser kernel parses the tag of the page, creates the dom object, and waits for the content of the tag to be displayed
  • Click (): bind click events
  • mouseover(): mouse in event
  • mouseout(): mouse out event
  • Bind (): you can bind one or more events to an element at one time, and multiple event names are separated by spaces
  • one (): the usage is the same as bind, but the bound event will respond only once
  • Unbind(): opposite to the bind method, unbind the event
  • on (): binding event, which can be used to bind the events of all elements matched by the selector, even if this element is dynamically created after the page is loaded

Prevent event bubbling: return false in child element events

Event object: declare the parameter event in the bound event function to get the object when the event is triggered

Exercise: the picture moves with the mouse

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style type="text/css">
        img{
            width: 100px;
        }
        #showBig{
            display: none;
        }
    </style>
    <title>Title</title>  <script src="../script/jquery-3.5.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#small").bind("mouseover mouseout mousemove",function (e) {
                if(e.type=="mouseover"){
                    $("#showBig").show();
                }else if(e.type=="mouseout"){
                    $("#showBig").hide();
                }else {
                    var x = e.originalEvent.pageX;
                    var y = e.originalEvent.pageY;
                    $("#showBig").offset({
                        top:y+10,
                        left: x+10
                    })
                }

            })
        });
    </script>
</head>
<body>
     <img id="small" src="../img/muc.png" />
        <div id="showBig">
            <img src="../img/muc.png" />
        </div>
</body>
</html>

Keywords: Javascript Front-end JQuery

Added by phpSensei on Mon, 14 Feb 2022 15:56:18 +0200