jQuery usage details day1

Posted by smarthouseguy on Mon, 20 Sep 2021 22:19:22 +0200

day01 - jQuery

1.1. Introduction to jquery

1.1.1 JavaScript Library

A JavaScript library, or library, is an encapsulated collection of specific methods and functions. To understand the library from the perspective of encapsulating a large number of functions, it is in this library that many predefined functions are encapsulated, such as animation, hide and show, such as obtaining elements.

Simple understanding: it is a js file that encapsulates our native js code and stores it in it. In this way, we can use these encapsulated functions quickly and efficiently.

For example, jQuery is to quickly and easily operate DOM, which is basically functions (Methods).

Common JavaScript libraries: jQuery, Prototype, YUI, Dojo, Ext JS, zepto on the mobile terminal, etc. these libraries encapsulate native JavaScript and are internally implemented in JavaScript. We mainly study jQuery.

In addition, the understanding of several concepts:

Library: js file, a tool for encapsulating native js (upgrading the original functions)

Plug in: js file, gadget, swiper (providing additional functions)

Framework: js file, big tool, bootstrap (providing additional functions)

1.1.2 concept of jquery

The general overview of jQuery is as follows:

  • jQuery is a fast and concise JavaScript library. Its design purpose is "write Less, Do More", that is, it advocates writing less code and doing more things.

  • j is JavaScript; Query query; It means querying js, encapsulating the DOM operation in js, and we can quickly query and use the functions inside.

  • jQuery encapsulates the common functional code of JavaScript and optimizes DOM operation, event processing, animation design and Ajax interaction.

  • Learning the essence of jQuery: learning to call these functions (Methods).

  • The purpose of jQuery is to speed up the development of front-end personnel. We can easily call and use it, so as to improve the development efficiency.

    Understanding: Jquery: JS has been upgraded, which is simpler and more awesome. It is a simplified version of JS.

1.1.3 advantages of jquery

  1. Lightweight. The core file is only tens of kb, which will not affect the page loading speed.
  2. Cross browser compatibility, basically compatible with the mainstream browsers.
  3. Chain programming, implicit iteration.
  4. Support for events, styles and animation, which greatly simplifies DOM operation.
  5. Support plug-in extension development. There are rich third-party plug-ins, such as tree menu, date control, rotation chart, etc.
  6. Free and open source.

1.2. Basic use of jquery

1.2.1 jQuery Download

jQuery's official website address: https://jquery.com/ , you can download the latest version on the official website.

Download of each version: https://code.jquery.com/

Version introduction:

1x: compatible with lower version browsers such as IE 678, and the official website will not be updated

2x: incompatible with IE 678 and other lower version browsers, and the official website will not be updated

3x: it is incompatible with IE 678 and other lower version browsers. It is the version mainly updated and maintained by the official

1.2.2. Experience jQuery

Steps:

  • Import jQuery file.
  • Insert the script tag at the end of the document to write the experience code.
  • $('div '). hide() can hide the box.

1.2.3. jQuery entry function

There are two common entry functions in jQuery:

// First: simple and easy to use***
$(function () {   
    ...  // This is the entrance to the completion of page DOM loading
}) ; 

// The second: cumbersome, but it can also be implemented (ready: ready, dom ready)
$(document).ready(function(){
   ...  //  This is the entrance to the completion of page DOM loading
});

Summary:

  1. After the DOM structure is rendered, we can execute the internal code. We don't have to wait until all external resources are loaded. jQuery helps us complete the encapsulation.
  2. Equivalent to DOMContentLoaded in native js.
  3. Unlike the load event in native js, the internal code is executed only after the page document, external js file, css file and picture are loaded.
  4. The first method is more recommended.

1.2.4. Top level objects in jquery$

  1. $is a nickname of jQuery, which can be replaced by jQuery in code, but generally for convenience, $.
  2. $is the top-level object of jQuery, which is equivalent to window in native JavaScript. By wrapping the element into a jQuery object with $, you can call the method of jQuery.

1.2.5. jQuery object and DOM object

The elements obtained by using jQuery method are different from those obtained by native JS. The summary is as follows:

  1. The object obtained with native JS is the DOM object
  2. The element obtained by the jQuery method is the jQuery object.
  3. The essence of jquery object is: the object generated by wrapping DOM objects with $(jquery object is a pseudo array and stores DOM objects one by one) * * *.

be careful:

Only jQuery objects can use the jQuery method, and DOM objects use the native JavaScirpt method.

1.2.6. jQuery object and DOM object conversion***

  • DOM objects and jQuery objects can be converted to each other.
  • Because the native js is larger than jQuery, some of the native properties and methods are not encapsulated by jQuery.
  • To use these properties and methods, you need to convert the jQuery object into a DOM object.
  • code:
// 1. There is only one method to convert DOM objects into jQuery objects
var box = document.getElementById('box');  // Get DOM object
var jQueryObject = $(box);  // Convert DOM objects to jQuery objects

// 2. There are two methods to convert jQuery objects to DOM objects:
//   2.1 jQuery object [index value]
var domObject1 = $('div')[0]

//   2.2 jQuery object. Get (index value)
var domObject2 = $('div').get(0)
 

Note: the jquery object is a pseudo array containing dom objects***

1.3. jQuery selector

There are many ways for native JS to obtain elements, which are very complex, and the compatibility is inconsistent. Therefore, jQuery encapsulates us to make the acquisition of elements unified.

1.3.1. Foundation selector***

$("selector")   //  Just write CSS selector directly inside, but use quotation marks 

The basic selector is shown in the following figure:

1.3.2. Level selector***

The two most commonly used level selectors are descendant selectors and descendant selectors.

The selector is shown in the figure below:

Base selector and level selector case codes

<body>
    <div>I am div</div>
    <div class="nav">I am nav div</div>
    <p>I am p</p>
    <ul>
        <li>I am ul of</li>
        <li>I am ul of</li>        
        <li>I am ul of</li>
    </ul>
    <script>
        $(function() {
            console.log($(".nav"));
            console.log($("ul li"));
        })
    </script>
</body>

1.3.3. Filter selector

Filter selector, as the name suggests, is to select the one that meets the conditions among all options for filter selection. Common are as follows:
Syntax: basic selector / level selector: keyword (: before colon can be label selector, class selector, level selector)

Understanding: filter selector to filter from a collection.

Case code

<body>
    <ul>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
    </ul>
    <ol>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
        <li>Select several from multiple</li>
    </ol>
    <script>
        $(function() {
            $("ul li:first").css("color", "red");
            $("ul li:eq(2)").css("color", "blue");
            $("ol li:odd").css("color", "skyblue");
            $("ol li:even").css("color", "pink");
        })
    </script>
</body>

1.3.4. Screening method***


Important to remember: parent() children() find() siblings() eq()

be careful:

In the above methods, the parameters of children, find and sliblings are strings, representing selectors

Understanding: why do children have parameters?

For example, there are two p's and two a's under Div. if you want to get the sons named P, you can get them through $('div '). children('p')

Summary:

// Offspring selection
$('ul>li');
$('ul').children('li');
// Offspring selection
$('ul li');
$('ul').find('li');

//Select a
$("ul li:eq(2)");
$("ul li").eq(2);
// The filter method is more used than the selector because it is more flexible (variables can be used easily)
// For example, an uncertainty to be selected is represented by the variable index
$("ul li:eq("+index+")").css("color", "blue");
$("ul li").eq(index).css("color", "blue");


// If the element to get is determined in the program, the hierarchical selector and filter selector are used
// If the program is uncertain about the element to get, the filter method is used

1.3.5. Knowledge paving***

  • jQuery style
$('div').css('attribute', 'value')    
  • Exclusive thought in jQuery
// If you want to choose one more effect, exclusive thought: set the style for the current element and clear the style for the other sibling elements.
$(this).css("color","red");
$(this).siblings().css("color","");
  • Implicit iteration (quiet traversal, automatic traversal within jquery)
// The process of traversing internal DOM elements (stored in pseudo array form) is called implicit iteration// Simple understanding: loop through all the matched elements and execute the corresponding methods instead of us, which simplifies our operation and facilitates our call.
$('div').hide();  // All div s in the page are hidden without circular operation. / / in the previous js, direct operation on a group of objects is not allowed, and only one element object can be operated
var divs = document.getElementsByTagName('div');
divs.style.backgroundColor = 'red'; // Error, style is a property of a dom object and cannot be called through a pseudo array
divs[0].style.backgroundColor = 'red'; // correct

Note: why is the jquery object a pseudo array because of implicit iteration

  • Chain programming (this knowledge point is not required to be mastered, but can be understood)
// Chain programming is to save code and look more elegant.
$(this).css('color', 'red').siblings().css('color', ''); $(this).css();// The caller is returned
$(this).siblings();// Go back to my brothers and sisters
//jq's operation methods: css(),hide(),show(), events, etc. will return the caller (operation method, implicit iteration) / / jq's filtering method will return the filtered object. Non filter method (operation method), which returns the caller (jq object)

1.3.6. Case: Taobao clothing boutique case

Train of thought analysis:

1. Core principle: when the mouse passes a small li in the box on the left, the corresponding pictures in the box in the content area will be displayed, and the other pictures will be hidden.

2. You need to get the index number of the current small li to display the picture corresponding to the index number

3.jQuery gets the index number $(this).index() of the current element

4. The corresponding picture in the middle can be selected by eq(index) method

5. Display element show() hide element hide()

code:

<script>
    $(function() {       
 // 1. The mouse passes through the small li on the left
          $("#left li").mouseover(function() {
          // 2. Get the index number of the current small li
           var index = $(this).index(); // The element is added with an index by default in Jquery, which is obtained through the index() method 
          console.log(index);           
    // 3. Let's just show the corresponding index number of the box on the right 	// $ ("#content div").eq(index).show();
   // 4. Hide the rest of the pictures (that is, other brothers)
   // $("#content div").eq(index).siblings().hide();
   // Chain programming
    $("#content div").eq(index).show().siblings().hide();        
    })    
  })
</script>

1.4. jQuery style operation***

There are two common style operations in jQuery: css() and set class style methods

1.4.1. Method 1: operate css method

jQuery can use css methods to modify simple element styles; You can also manipulate classes to modify multiple styles.

The following three forms are commonly used:

// 1. If the parameter only writes the property name, the property value is returned
var strColor = $(this).css('color');

// 2. Parameters are attribute names, attribute values, separated by commas. They are used to set a set of styles. Attributes must be quoted. If the value is a number, it can not be followed by units and quotation marks
$(this).css('color', 'red');

// 3. The parameter can be in the form of object, which is convenient for setting multiple groups of styles. Attribute names and attribute values are separated by colons, and attributes can not be quoted
$(this).css({ "color":"white","font-size":"20px"});

function css(){
    var length  = paramters.length
    if(length==1){// An attribute name parameter that gets parameters and sets objects with multiple groups of attributes
        if (typeof(paramters[0]) == 'string' ){
            // Get operation
        }else{
            // Setting operation (object form)
        }
    }else{
        //Set a set of properties
    }
}

Note: css() is mostly used to operate when there are few styles, but it is inconvenient when there are many styles.

css() operates on an inline style (style attribute)

1.4.2. Method 2: set class style method

The function is the same as the previous classList. You can manipulate the class style. Pay attention not to add points to the parameters in the operation class.

There are three common methods for setting class styles:

// 1. Add class
$("div").addClass("current");  // className,classList

// 2. Delete class
$("div").removeClass("current");

// 3. Switching class
$("div").toggleClass("current");

// toggleClass is achieved through addClass, removeClass and hasClass
// If this element has current, it should be removed
if($('#div01').hasClass('current')){
    $('#div01').removeClass('current');
}else{
    // If this element does not have current, it should be added
    $('#div01').addClass("current")
}

be careful:

  1. The method of setting class style is more suitable for multi style operation, and can make up for the deficiency of css().
  2. The className in the native JS will overwrite the original class name in the element. The class operation in jQuery only operates on the specified class and does not affect the original class name.

1.4.3. Case: tab column switching

Train of thought analysis:

1. Click the li in the upper part to add the current class to the current li and remove the other classes.

2. Click to get the index number of the current li

3. Display the items in the corresponding index number in the lower part and hide the other items

code:

<script>
    $(function() {
    // 1. Click li in the upper part to add the current class to the current li and remove the other classes
    $(".tab_list li").click(function() {
        // Chain programming operation
        $(this).addClass("current").siblings().removeClass("current");
        // 2. Click to get the index number of the current li
        var index = $(this).index();
        console.log(index);
        // 3. Display the items in the corresponding index number in the lower part and hide the other items
        $(".tab_con .item").eq(index).show().siblings().hide();
    });
})
</script>

1.5. jQuery effect

jQuery encapsulates many animation effects. The most common are as follows:

  • Display and hide: show() / hide() / toggle();
  • Transfer in and out: slideDown() / slideUp() / slideToggle();
  • Fade in and fade out: fadeIn() / fadeOut() / fadeToggle() / fadeTo();
  • Custom animation: animate();

be careful:

  • Animation or effects will be executed once triggered. If triggered multiple times, multiple animation or effects will be queued for execution.

  • jQuery provides us with another method to stop the animation queue: stop();

1.5.1. Show hide (diagonal animation)

There are three common methods to show and hide Animation: show() / hide() / toggle();

The syntax specification is as follows:


Code demonstration

<body>
    <button>display</button>
    <button>hide</button>
    <button>switch</button>
    <div></div>
    <script>
        $(function() {
            $("button").eq(0).click(function() {
                $("div").show(1000, function() {
                    alert(1);
                });
            })
            $("button").eq(1).click(function() {
                $("div").hide(1000, function() {
                    alert(1);
                });
            })
            $("button").eq(2).click(function() {
              $("div").toggle(1000);
            })
            // In general, we can directly display and hide without adding parameters
        });
    </script>
</body>

1.5.2. Sliding in and out (sliding door, height animation)

There are three common methods for sliding in and out animation: slideDown() / slideUp() / slideToggle();

The syntax specification is as follows:



Code demonstration

<body>
    <button>Pull down sliding</button>
    <button>Pull up sliding</button>
    <button>Switching sliding</button>
    <div></div>
    <script>
        $(function() {
            $("button").eq(0).click(function() {
                // Slide down ()
                $("div").slideDown();
            })
            $("button").eq(1).click(function() {
                // Slide up
                $("div").slideUp(500);
            })
            $("button").eq(2).click(function() {
                // Slide toggle ()
                $("div").slideToggle(500);
            });
        });
    </script>
</body>

Case: drop down menu

<script>
    $(function() {
    // Mouse passing
    // $(".nav>li").mouseover(function() {
    //     //$(this) jQuery the current element this without quotation marks
    //     //show() show element hide() hide element
    //     $(this).children("ul").slideDown(200);
    // });
    // //Mouse away
    // $(".nav>li").mouseout(function() {
    //     $(this).children("ul").slideUp(200);
    // });
    // 1. Event switching hover is the compound writing method of mouse passing and leaving
    // $(".nav>li").hover(function() {
    //     $(this).children("ul").slideDown(200);
    // }, function() {
    //     $(this).children("ul").slideUp(200);
    // });
    // 2. Event switching hover if only one function is written, this function will be triggered when the mouse passes and when the mouse leaves
    $(".nav>li").hover(function() {
        $(this).children("ul").slideToggle();
    });
})
</script>

1.5.3 fade in and fade out (transparency animation)

There are four common methods to fade in and out animation: fadeIn() / fadeOut() / fadeToggle() / fadeTo();

The syntax specification is as follows:



Code demonstration

<body>
    <button>Fade in effect</button>
    <button>Fade out effect</button>
    <button>Fade in and fade out switch</button>
    <button>Modify transparency</button>
    <div></div>
    <script>
        $(function() {
            $("button").eq(0).click(function() {
                // Fade fadeIn()
                $("div").fadeIn(1000);
            })
            $("button").eq(1).click(function() {
                // Fade fadeOut()
                $("div").fadeOut(1000);
            })
            $("button").eq(2).click(function() {
                // Fade in and fade out switch fadeToggle()
                $("div").fadeToggle(1000);
            });
            $("button").eq(3).click(function() {
                //  Modify the transparency fadeTo(), the speed and transparency must be written
                $("div").fadeTo(1000, 0.5);
            });
        });
    </script>
</body>

1.5.4 custom animation***

Custom animation is very powerful. You can simulate all the above animations through parameter transfer. The method is: animate();

The syntax specification is as follows:

Code demonstration

<body>
    <button>Move</button>
    <div></div>
    <script>
        $(function() {
            $("button").click(function() {
                $("div").animate({
                    left: 500,
                    top: 300,
                    opacity: .4,
                    width: 500
                }, 500);
            })
        })
    </script>
</body>

1.5.5 Stop Animation queuing***

Animation or effects will be executed once triggered. If triggered multiple times, multiple animation or effects will be queued for execution.

The method to stop animation queuing is: stop();

  • The stop() method is used to stop an animation or effect.
  • stop() is written in front of the animation or effect, which is equivalent to stopping and ending the last animation.

Summary: call stop() before using animation each time.

1.5.6. Event switching

jQuery adds a new event hover(); The function is similar to the pseudo class in css: hover. The introduction is as follows

grammar

hover([over,]out)     // Where over and out are two functions
  • Over: move the mouse over the element to trigger the function (equivalent to mouseenter)
  • Out: the function to be triggered when the mouse moves out of the element (equivalent to mouseleave)
  • If you write only one function, it will be triggered when the mouse passes and leaves

hover event and stop animation arrangement case

<body>
    <ul class="nav">
        <li>
            <a href="#"> microblog</a>
            <ul><li><a href="">private letter</a></li><li><a href="">comment</a></li><li><a href="">@I</a></li></ul>
        </li>
        <li>
            <a href="#"> microblog</a>
            <ul><li><a href="">private letter</a></li><li><a href="">comment</a></li><li><a href="">@I</a></li></ul>
        </li>
    </ul>
    <script>
        $(function() {
            // Mouse passing
            // $(".nav>li").mouseover(function() {
            //     //$(this) jQuery the current element this without quotation marks
            //     //show() show element hide() hide element
            //     $(this).children("ul").slideDown(200);
            // });
            // //Mouse away
            // $(".nav>li").mouseout(function() {
            //     $(this).children("ul").slideUp(200);
            // });
            // 1. Event switching hover is the compound writing method of mouse passing and leaving
            // $(".nav>li").hover(function() {
            //     $(this).children("ul").slideDown(200);
            // }, function() {
            //     $(this).children("ul").slideUp(200);
            // });
            // 2. Event switching hover if only one function is written, this function will be triggered when the mouse passes and when the mouse leaves
            $(".nav>li").hover(function() {
                // The stop method must be written before the animation
                $(this).children("ul").stop().slideToggle();
            });
        })
    </script>
</body>

1.5.7. Case: King glory accordion effect

Train of thought analysis:

1. When the mouse passes a small li, there are two steps:

2. The current small li width changes to 224px, while the small picture inside fades out and the large picture fades in

3. For the other brothers, the small li width becomes 69px, the small picture fades in and the large picture fades out

code:

<script type="text/javascript">
    $(function() {
    // When the mouse passes a small li, there are two steps:
    $(".king li").mouseenter(function() {
        // 1. The current small li width changes to 224px, while 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. For the other brothers, the small li width becomes 69px, the small picture fades in and the large picture fades out
        $(this).siblings("li").stop().animate({
            width: 69
        }).find(".small").stop().fadeIn().siblings(".big").stop().fadeOut();
    })
});
</script>

1.6. Summary


The top-level object $in jquery is special. It can be used as an object or a function***

  1. Use as a function

(1). If an anonymous function is passed, it is used as the entry function (DOMContentLoaded)

(2) if a DOM object is passed, it is used as a type conversion to convert the DOM object into a jq object

(3). If a css selector (string) is passed, it is used as an element to get

(4). If it is a string of html content, it is used as an element object

  1. $is a function and an object, which can call methods directly
$.each(arr, function(i, ele) {
    console.log(i);
    console.log(ele);
    })

Note:
1. $('video ') [0].play() // jquery object is a pseudo array, and all stored in the pseudo array are Dom objects
2. $(“ul li”).css(“color”, “red”); // Traverse all element objects in the pseudo array and set the style in turn (implicit iteration)
3. Get the current js element object, this - $(this) convert the current js element object this to jq's current element object

Topics: Javascript JQuery