[jQuery in front end tutorial series] 02_ Introduction to jQuery and understanding of design ideas

Posted by chetanmadaan on Wed, 05 Jan 2022 07:35:56 +0100

jQuery video through train from getting started to becoming proficient:

        JQuery video tutorial, from introduction to actual combat, interactive actual combat between native ajax and jQuery ajax, easy to understand!

Getting started with jQuery

jQuery download and import

jQuery Download

  • Official website address: jQuery

We can use the official website jQuery perhaps Download all versions of jquery (real-time update) Download jQuery;

Introduction of jQuery

Using jQuery is very simple. You only need to introduce the downloaded jQuery class library between < head > < / head > of the html page. For example:

        <script type="text/javascript" src="jquery.min.js"></script>

Note: tag pairs that introduce jquery cannot write js code
After importing the jQuery framework file, you can use the selector and various functions of jQuery.  

jQuery first experience

jQuery implementation animation

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            margin-top: 10px;
            margin-left: 100px;
        }

        #bigDiv {
            width: 183px;
            height: 550px;
            overflow: hidden;
            background: url("images/customer.jpg");
        }

        #imgDiv {
            margin: 210px auto 0;
            text-align: center;
            font-size: 14px;
            user-select: none;
            cursor: pointer;
            color: orangered;
            font-weight: bold;
        }

        #imgDiv>img {
            margin-top: -3px;
            cursor: pointer;
        }

        #imgDiv p {
            line-height: 26px;
        }

        #imgDiv>div {
            display: none;
        }
    </style>
</head>

<body>
    <div id="bigDiv">
        <div id="imgDiv">
            <img src="images/reg.jpg" alt="">
            <div>
                <p>Click Register</p>
                <p>authentication center</p>
            </div>
            <img src="images/buy.jpg" alt="">
            <div>
                <p>consulting service</p>
                <p>complaint</p>
                <p>report</p>
                <p>refund</p>
            </div>
            <img src="images/sale.jpg" alt="">
            <div>
                <p>Security Center</p>
                <p>Logistics Centre</p>
                <p>Capital flow</p>
                <p>Dispute handling</p>
            </div>
            <img src="images/person.jpg" alt="">
            <div>
                <p>Modify data</p>
                <p>Account appeal</p>
            </div>
        </div>
    </div>
    <script src="jquery.min.js"></script>
    <script>
        $("#imgDiv>img").click(function () {
            $(this).next("div").slideToggle(300).siblings("div").slideUp(300);
        })
    </script>
</body>

</html>

Compared with the previous JS code, do you think the jQuery implementation is very concise? The purpose of jQuery is: write less, do more;

Implicit iteration

Inside the method, loop traversal will be performed for all matched elements to execute the corresponding method, instead of us looping, simplifying our operation and facilitating our call. This is called implicit iteration.

jQuery object is an array of objects (pseudo array). Calling a method on it is actually calling this method iteratively for each element in the array, which is equivalent to using a loop to traverse each element and call this method.

For example, add click events: for multiple elements obtained by DOM objects, we need to add events to them respectively through a loop, but jQuery objects do not need to. As long as we call the click event method in jQuery, we can add events to all elements.

// JS adds a mouse click event to all a tags obtained:
var aArr=document.getElementsByTagName('a');
for(var i=0;i<aArr.length;i++){
	aArr[i].onclick=function(){
		alert("click me!");
	}
}

// jQuery adds mouse click events to all a tags obtained
$("a").click(function(){
	alert("click me!");
});

Chain programming

Chain programming is to pass multiple operations (multiple lines of code) through the dot "." Link together into a code.

Let's start with an example:

$("#myphoto").css("border","2px solid #FF0000").attr("alt","good");

For a jQuery object, the css() function is called to modify the style, and then the attr() function is used to modify the attributes. This call is like a chain, so it is called "chain operation".

Chain operation can make the code concise, because it can often realize the tasks that can be completed by more than one statement in one statement. For example, if you do not use chained operations, you need two statements to complete the above tasks:

$("#myphoto").css("border","2px solid #FF0000");

$("#myphoto").attr("alt","good");

In addition to increasing the amount of code, the selector is called twice to reduce the speed.

However, the chain operation should not be too long, otherwise the statement will be difficult to understand, because it is not easy to view the current state of the jQuery object, especially if it involves the addition and deletion of elements in the jQuery object.

Not all jQuery functions can use chained operations. This is related to the principle of chain operation. The reason why chain operation can be implemented is that each function returns the jQuery object itself.

Chain programming can make the code readable. The principle of chain programming is to return a this object, that is, return itself to achieve the chain effect

jQuery thought understanding

design idea

The basic design idea and main usage of jQuery is to "select a web page element and then perform some operation on it". This is the fundamental feature that distinguishes it from other Javascript libraries.

The first step in using jQuery is often to put a selection expression into the constructor jQuery() (abbreviated as $), and then get the selected element.

The second design idea of jQuery is to provide various powerful filters to filter the result set and narrow the selection results

The third design idea of jQuery is that after the web page element is finally selected, a series of operations can be carried out on it, and all operations can be connected together and written in the form of a chain

The fourth design idea of jQuery is to use the same function to complete the getter and setter, that is, the integration of "valuer" and "evaluator". Whether to take value or assign value depends on the parameters of the function.

The fifth design idea of jQuery is to provide two groups of methods to manipulate the position and movement of elements in web pages. One group of methods is to move the element directly, and the other group of methods is to move other elements to make the target element reach the position we want.

jQuery design idea 6: in addition to operating on the selected elements, it also provides some tool methods (utilities) independent of the elements. You can use these methods directly without selecting the element.

The seventh design idea of jQuery is to bind events directly to web page elements.

Finally, jQuery allows objects to render some special effects.

$sign of jQuery

The characters allowed in JS naming specification are: numbers, letters, underscores

<script src="jquery.js"></script>
<script type="text/javascript">
        console.log($);
        console.log(jQuery);
        console.log($===jQuery);
</script>

$.

The JS naming convention allows the following characters as the beginning of variable naming: letters, underscores, $; However, it is not allowed to start variable names with numbers.

var $ = "I'm a string";

var $ = 123;

function $() {
    alert("I'm a function $");
}

jQuery uses $because it is concise, different from other characters and easy to remember.

JQuery takes up two variables: $and jQuery.

When printing $and jQuery in Code:

<script src="jquery.js"></script>
<script type="text/javascript">
        console.log($);
        console.log(jQuery);
        console.log($===jQuery);
</script>

The results displayed are as follows:

From the results, we can conclude that $represents jQuery.

So how to understand the $symbol in jQuery?

$actually represents a function name, as shown below:

$() //Call our custom function above$

$(document).ready(function () {

}) //Call entry function

$(function () {

}) //Call entry function

$("#Container ") / / call the element whose id attribute is container

$("div") //Get all div tag elements

As shown above, the $function in jQuery makes different calls to implement different functions and return jQuery objects according to different incoming parameters.

JQuery, a js library, provides another function besides $: jQuery.

Relationship between jQuery function and $function: jQuery = = $.

Mutual conversion of jQuery object and DOM object

When learning jQuery for the first time, you often can't distinguish which are jQuery objects and which are DOM objects. Therefore, you need to understand jQuery objects, DOM objects and the relationship between them.

DOM object

Document object model (DOM) is a standard programming interface recommended by W3C organization to deal with extensible markup language.

  • DOM is actually a document model described in an object-oriented manner. DOM defines the objects needed to represent and modify documents, the behavior and properties of these objects, and the relationships between these objects.

  • Through DOM, you can access all HTML elements, along with the text and attributes they contain. The contents can be modified and deleted, and new elements can be created.

  • DOM is platform and programming language independent. It can be used by any programming language such as Java, JavaScript and VBScript.

  • DOM objects, that is, the objects we get with traditional methods (javascript).

  • DOM is exactly a standard for document objects (document object model). The standard only defines properties and method behavior.

To put it simply: DOM objects refer to the results returned by manipulating DOM with JavaScript.

jQuery object

JQuery object is the object generated by wrapping DOM objects through jQuery.

JQuery object is unique to jQuery. It can use the methods in jQuery, but it cannot use the DOM methods; Conversely, DOM objects cannot use jQuery methods.

To put it simply: jQuery object here refers to the result returned by using the method of operating DOM provided by jQuery.

After getting the DOM object, jQuery encapsulates it to have the jQuery object of the jQuery method. To put it bluntly, it repackages the DOM object.

Case: DOM operation return value and jQuery operation return value

<script src="jquery.js"></script>

<div>I'm the first div</div>
<div class="box">I'm the second div</div>
<div id="box">I'm the third div</div>
<div class="box">I'm the fourth div</div>
<div>I'm the fifth div</div>
<script>
    // Get page element nodes through js
    var box = document.getElementById("box");
    var cboxs = document.getElementsByClassName("box");
    var divs = document.getElementsByTagName("div");
    console.log(box);
    console.log(cboxs);
    console.log(divs);
    console.log("------------------------")

    // Get page elements through jQuery
    var jbox = $("#box");
    var jCboxs = $(".box");
    var jdivs = $("div");
    console.log(jbox);
    console.log(jCboxs);
    console.log(jdivs);

    var arr = [1, 2, 3, 4, 5];
    console.log(arr)
</script>

Case: jQuery object and DOM object API cannot be mixed and matched

// Get page element nodes through js
var box = document.getElementById("box");
// The DOM object calls the DOM API. There is no problem
box.style.background = "red";
// The DOM object does not have css(), and an error box is reported css is not a function
// box.css("background", "yellow");

// Get page elements through jQuery
var jbox = $("#box");
// The jQuery object calls the jQuery API. There is no problem
jbox.css("background", "yellow");
// The jQuery object calls DOM API. There is a problem: Cannot set property 'background' of undefined
jbox.style.background = "red";

Convert jQuery object to DOM object

JQuery objects cannot use the methods in DOM, but if you are not familiar with the methods provided by jQuery objects, or jQuery does not encapsulate the desired methods, you have to use DOM objects. There are two processing methods.

(1) jQuery object is an array like object. You can get the corresponding DOM object through the [index] method. For example, if there is only one DIV with the class name "bind", the console will output console log($(".bind"))

As shown in the figure, through the debugging tool, we can see that the jQuery object is a class array object, and we can obtain the DOM object through $(". bind")[0].

(2) another method is provided by jQuery itself, and the corresponding DOM object is obtained through the get(index) method. It's still up there bind object, we can use $(". bind") Get (0) get DOM object. As shown in the figure:

Convert DOM object to jQuery object

For a DOM object, just wrap the DOM object with $() to get a jQuery object. The method is $(DOM object). After conversion, you can use any method in jQuery.

Note: normally used jQuery objects are created through the $() function, which is a manufacturing factory of jQuery objects.

 

All these reflect jQuery's encapsulation of js!

[thinking] what is the difference between JS and jQuery?

How to use jQuery

Use steps

  • The first step is to import the jQuery file

  • Step 2: entry function

  • Step 3 write function code

Version introduction

        1.x: Compatible with ie678, it is the most widely used. The official only does BUG maintenance, and the functions are no longer added. Therefore, for general projects, use 1 X version is OK. Versions 1.8.3 and 1.11.3 are recommended

        2.x: It is not compatible with ie678 and is rarely used. The official only does BUG maintenance, and the functions are no longer added. If you do not consider compatibility with lower versions of browsers, you can use 2 x

        3.x: Not compatible with ie678, only the latest browsers are supported. Unless otherwise specified, 3.1.1 will not be used X version. Many old jQuery plug-ins do not support this version. At present, this version is the official version mainly updated and maintained.

min: compressed version. After compression, the volume will be smaller

Compression refers to removing all comments, spaces and newlines, and replacing variable names with shorter characters as much as possible.

The main purpose of compression is to make the file smaller.

During normal development, you can use either of these two files; However, when the project goes online, the compressed version is recommended.

Note: points for attention

Point 1: before using jQuery, first introduce the jQuery file to the page

If the jQuery file is not referenced before using jQuery, an error will be reported:

The second point: the src path must be written correctly

If the src path is written incorrectly, an error will also be reported:

jQuery entry function

The entry function of native JS refers to: window Onload = function() {}: as follows:

<script type="text/javascript">
	//The entry function of native js. All contents on the page are loaded before execution.
	//Not only wait for the text to load, but also wait for the picture to load before executing the function.
    window.onload = function () {
        alert("hello");
    }
</script>

The entry function of jQuery can be written in the following ways:

Writing method:

<script type="text/javascript">
	//This function can be executed when the document is loaded and the image is not loaded.
    $(document).ready(function () {
        alert("hello");
    })
</script>

<script type="text/javascript">
    //This function can be executed when the document is loaded and the image is not loaded.
    $(function () {
        alert("hello");
    })
</script>

<script type="text/javascript">
    //When the document is loaded and the picture is loaded, execute this function.
    $(window).ready(function () {
        alert("hello");
    })
</script>

The difference between jQuery entry function and js entry function

Difference 1: the number of writing is different:

(1) the entry function of JS can only occur once. If it occurs multiple times, there will be the problem of event coverage.

(2) the entry function of jQuery can occur any number of times, and there is no event coverage problem.

Difference 2: different execution time:

(1) the JS entry function is executed after all file resources are loaded. These file resources include: page documents, external JS files, external CSS files, pictures, etc.

(2) the entry function of jQuery is executed after the document is loaded. Document loading means that after the DOM tree is loaded, you can operate the DOM without waiting for all external resources to load successfully.

Ps: the order of document loading is: from top to bottom, parsing and executing at the same time.

Topics: Javascript Front-end JQuery