preface

I haven’t learned JQuery before, because you can’t manipulate the DOM directly in Vue, React, etc., but JQuery is a great Swiss Army knife if you need to work directly with the DOM. JQuery is a lightweight JavaScript library that encapsulates a number of functions and methods to simplify JS operations, such as DOM manipulation, event handling, animation design, and Ajax interaction.

How to introduce JQuery

You can download the latest 3.x version of JQuery from the official website, but you can import BootCDN through CDN during the learning phase, like this:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body></body>
</html>
Copy the code

JQuery’s top-level object

$() is an alias for JQuery. JQuery is essentially a function that performs different functions depending on the type of argument you pass in. JQuery is also an object with many methods mounted on it.

For example, if $() passes a function, it defines a DomContentLoaded event handler. Normally, we write logic inside the function to ensure that the DOM is accessible.

<body>
    <script>
      // $is an alias for JQuery
      $(function () {
        console.log('DomContentLoaded');
      });
      jQuery(function () {
        console.log('DomContentLoaded');
      });
    </script>
</body>
Copy the code

JQuery object and DOM object

When we use JQuery to manipulate the DOM, we don’t get a native DOM object, but a wrapped JQuery object. This object is a pseudo-array of DOM objects wrapped around it. Because JQuery is compatible with retrieving one or more DOM objects, we wrap the pseudo-array objects around it. Take this example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      console.dir($('ul li'));
    </script>
  </body>
Copy the code

We get the Li tag element, and we get three DOM objects wrapped in a pseudo-array of JQuery objects.

DOM objects are converted to JQuery objects

Because DOM objects and JQuery objects can use different methods, sometimes we need to convert them to each other. DOM objects can be converted to JQuery objects with only $(DOM object), as in this example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      let ul = document.querySelector('ul');
      console.dir(ul);
      console.dir($(ul));
    </script>
  </body>
Copy the code

JQuery object to DOM object

The JQuery object is a pseudo-array. Each element of the array is a native DOM object, so we can get the DOM object by indexing it. There are two main ways to get the DOM object: [index] or get(index).

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      console.dir($('ul li') [0]);
      console.dir($('ul li').get(0));
    </script>
  </body>
Copy the code

JQuery for DOM

The most typical function of JQuery is convenient DOM manipulation. To achieve DOM manipulation, the first step is to obtain DOM. JQuery obtains DOM in a similar way to Document.querySelector (), both through CSS selector. But JQuery adds some extra selectors and methods to make it easier to select DOM elements, as we’ll see below.

CSS selectors

The most direct way to get a DOM element is $(‘ CSS selector ‘), as in this example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      $('ul'); // Get ul element
      $('ul li'); // Get the li element below ul
    </script>
  </body>
Copy the code

Here are some common CSS selectors:

The name of the usage describe
The ID selector $('#id') Gets the element with the specified ID
Class selectors $('.class') Gets all elements of the same class
The selector $(' * ') Get all elements
Label selector $('div') Gets all elements of the same class of tags
Union selector $('div,p,li') Get multiple elements
Intersection selector $('div.header') Intersection elements that satisfy more than one condition at a time
Child selector $('ul>li') Gets a direct descendant element, especially a son element
Descendant selector $('ul li') Gets all descendant elements, including all descendant elements such as grandchildren and great-grandchildren

Implicit iteration

The JQuery object is a pseudo-array, and when we apply methods to that object, they are applied to all DOM elements by default, which is implicit iteration. Take this example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      $('ul li').css('color'.'red');
    </script>
  </body>
Copy the code

Filter selector

JQuery extends CSS selectors. These selectors are only available in JQuery.

grammar usage describe
:first $('li:first') Gets the first Li element
:last $('li:last') Gets the last Li element
:eq(index) $('li:eq(2)') Get the li element with index 2, starting at 0
:odd $('li:odd') Gets the element whose index number is odd
:even $('li:even') Gets the element whose index number is even

Let’s look at an example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      $('ul li:first').css('color'.'red');
      $('ul li:last').css('color'.'blue');
      $('ul li:eq(1)').css('color'.'green');
    </script>
  </body>
Copy the code

These selectors are similar to structure selectors in CSS and should be used normally, but remember that these selectors cannot be used in CSS, only in JQuery.

Screening method

In addition to selectors, JQuery provides some filtering methods, mainly as follows:

grammar usage describe
parent() $('li').parent() Look for the parent
children(selector) $('ul').children('li') Gets the immediate descendant element, equivalent to $(‘ul>li’)
find(selector) $('ul').find('li') Gets all descendant elements, equivalent to $(‘ul li’)
siblings(selector) $('li.first').siblings('li') Find sibling nodes, not including yourself
nextAll([selector]) $('li.first').nextAll() Finds sibling nodes following the current element, selectors optional
prevtAll([selector]) $('li.first').prevtAll() Finds the sibling node before the current element, selectors optional
hasClass(class) $('div').hasClass('protected') Determines whether the current element contains a specific class, and returns true if it does
eq(index) $('li').eq(2) Select the element with the specified index, as in$('li:eq(2)')

Let’s look at an example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      $('li:first').parent().css('border'.'1px solid green');
      $('ul').children().css('color'.'red');
      $('li').eq(1).siblings().css('backgroundColor'.'#ccc');
    </script>
  </body>
Copy the code

Jquery-style manipulation

JQuery’s manipulation of styles encapsulates the native DOM manipulation of style and class, but is much easier to use.

Get the CSS style

We can use $(‘selector’).css(‘attr’) to get the style of the element, as in the following example:

  <body>
    <ul>
      <li style="color: red">1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      console.log($('li:first').css('color'));
    </script>
  </body>
Copy the code

Setting CSS Styles

$(‘selector’).css(‘attr’, value), or $(‘selector’).css({attr1: value1, attr2: value2}), as in this example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      $('li:first').css('color'.'red');
      $('ul').css({
        border: 'solid 1px green'.listStyle: 'none'.// JQuery recognizes hump naming styles
      });
    </script>
  </body>
Copy the code

Manipulating styles through classes

JQuery provides three methods for manipulating a Class, including:

  • $('selector').addClass('class')Add the class
  • $('selector').removeClass('class')Delete the class
  • $('selector').toggleClass('class')Switch the class

Let’s take an example:

  <head>
    <style>
      .current {
        color: red;
      }
    </style>
  </head>
  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li class="current">3</li>
    </ul>
    <script>
      $('li:first').addClass('current');
      $('li:last').removeClass('current');
      $('li:last').click(function () {$(this).toggleClass('current'); // Toggle the current class when clicked, delete it if it exists, add it if it doesn't
      });
    </script>
  </body>
Copy the code

JQuery animation

JQuery provides a set of animation apis, but CSS animations are recommended for simple scenes, and JS animations are recommended only for complex animations that require flow control.

Show hidden

Showing or hiding elements is a common effect, and JQuery provides three apis, including the following:

  • $('selector').show([speed],[easing],[fn])According to
    • Speed: Indicates the speed. The value can be ‘slow’, ‘normal’, ‘fast’, or milliseconds, for example, 1000
    • Easing: Represents a easing function, such as fast and then slow, with the option ‘swing’/’ Linear ‘and the default’ Swing ‘
    • Fn: callback function after animation execution
  • $('selector').hide([speed],[easing],[fn])hidden
  • $('selector').toggle([speed],[easing],[fn])switch

Let’s look at an example:

  </head>
    <style>
      .menu {
        display: none;
        width: 200px;
        height: 200px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div>
      <button class="show">show</button>
      <button class="hide">hide</button>
      <button class="toggle">toggle</button>
      <div class="menu"></div>
    </div>
    <script>
      $('.show').click(function () {$('.menu').show(1000.function () {
          console.log('menu is shown');
        });
      });
      $('.hide').click(function () {$('.menu').hide(1000.function () {
          console.log('menu is hidden');
        });
      });
      $('.toggle').click(function () {$('.menu').toggle(1000.function () {
          console.log('menu is toggled');
        });
      });
    </script>
  </body>
Copy the code

Effect of sliding

The sliding effect refers to an element that slides up or down. JQuery also provides three apis, including the following:

  • $('selector').slideDown([speed],[easing],[fn])Down on
    • Speed: Indicates the speed. The value can be ‘slow’, ‘normal’, ‘fast’, or milliseconds, for example, 1000
    • Easing: Represents a easing function, such as fast and then slow, with the option ‘swing’/’ Linear ‘and the default’ Swing ‘
    • Fn: callback function after animation execution
  • $('selector').slideUp([speed],[easing],[fn])Fold up
  • $('selector').slideToggle([speed],[easing],[fn])switch

Use similar to show hide, no more examples.

The fading

Fade-in refers to changes in the transparency of an element. JQuery provides four apis, including the following:

  • $('selector').fadeIn([speed],[easing],[fn])Down on
    • Speed: Indicates the speed. The value can be ‘slow’, ‘normal’, ‘fast’, or milliseconds, for example, 1000
    • Easing: Represents a easing function, such as fast and then slow, with the option ‘swing’/’ Linear ‘and the default’ Swing ‘
    • Fn: callback function after animation execution
  • $('selector').fadeOut([speed],[easing],[fn])Fold up
  • $('selector').fadeToggle([speed],[easing],[fn])switch
  • $('selector').fadeTo(speed, opacity, [easing],[fn])Fade into the specified transparency
    • Opacity: indicates opacity and is a number between 0 and 1. Speed and opacity are mandatory

Custom animation

JQuery allows you to customize your animations, essentially setting the CSS style that you want to change, sort of like the TRANSITION animation in CSS, with just one API:

  • $('selector').animate(styles,[speed],[easing],[fn])
    • Styles: Name of the CSS style to change, passed as an object
    • Speed /easing/fn: same as above

Let’s take an example:

  <head>
    <style>
      .menu {
        position: absolute;
        width: 200px;
        height: 200px;
        background-color: green;
      }
    </style>
  </head>
  <body>
    <div>
      <button class="animate">animate</button>
      <div class="menu"></div>
    </div>
    <script>
      $('.animate').click(function () {$('.menu').animate(
          {
            left: '500px',},500
        );
      });
    </script>
  </body>
Copy the code

JQuery attribute Manipulation

Usually we need to get or set the value of a DOM element, such as the value of a form. JQuery provides three sets of apis to do this, including the following:

  • $('selector').prop('prop')Get built-in properties
  • $('selector').prop('prop', value)Setting built-in properties
  • $('selector').attr('attr')Gets custom attributes
  • $('selector').attr('attr', value)Set custom properties
  • $('selector').data('attr')Get JQuery cache data or as advocated in H5data-*Custom attributes, such asdata-indexYou just need to writedata(index)Can be
  • $('selector').data('attr', value)The data is cached on a specific DOM element, mounted on the DOM as an object property and not displayed in a tag

Prop and attr

Let’s start by comparing prop and ATTR. In native DOM operations, there are also two ways to manipulate attributes. One is through dom.attr and the other is through dom.getAttribute()/dom.setAttribute(). These are the same in most cases, with two exceptions:

  • Style property: When we passelement.styleWhen you get the property, you getCSSStyleDeclarationObject while passingelement.getAttribute('style')When you get the property, you get something similarbackground-color: redThe string
  • Event handler: When we passelement.onclickWhen you get the property, you getƒ onclick (event)Function object while passingelement.getAttribute('onclick')When you get the property, you get something similarconsole.log('click');The string

JQuery prop and attR can be used to obtain properties. Here is an example:

  <body>
    <div>
      <button class="animate" onclick="console.log('click');">animate</button>
      <div style="background-color: red" class="menu"></div>
    </div>
    <script>
      console.dir($('.menu').prop('style'));
      console.dir($('.animate').prop('onclick'));
      console.dir($('.menu').attr('style'));
      console.dir($('.animate').attr('onclick'));
    </script>
  </body>
Copy the code

So in general, we use prop for built-in properties and attR for custom properties, but there is no difference in setting properties between the two.

Method the data

The data method sets and retrieves cached data and a custom property in data-* format. Let’s look at an example:

  <body>
    <div>
      <button class="animate" data-age="14">animate</button>
      <div style="background-color: red" class="menu"></div>
    </div>
    <script>
      $('.animate').data('myName'.'zhangsan');
      console.dir($('.animate').data('myName'));
      console.dir($('.animate').data('age'));
    </script>
  </body>
Copy the code

JQuery content manipulation

In the native DOM, we can set the innerHTML, innerText, and value in the form, which are collectively called content operations. JQuery provides three sets of apis to do this, including the following:

  • $('selector').html()Get innerHTML
  • $('selector').html('html')Set the innerHTML
  • $('selector').text()To obtain the innerText
  • $('selector').text('text')Set the innerText
  • $('selector').val()Gets the value of the form element
  • $('selector').val(value)Set the value of the form element

Let’s look at an example:

  <body>
    <div>
      <div class="html"><span>hello jquery</span></div>
      <div class="text">hello jquery</div>
      <input class="val" value="hello jquery" />
    </div>
    <script>
      console.log($('.html').html());
      $('.html').html('<span>123</span>');
      console.log($('.text').text());
      $('.text').text('<span>123</span>');
      console.log($('.val').val());
      $('.val').val('123');
    </script>
  </body>
Copy the code

JQuery element manipulation

Let’s talk about how to iterate, create, add, and delete elements in JQuery.

Traverse elements

The JQuery object is a pseudo-array. All operations on the JQuery object implicitly iterate over each DOM element, but this iteration does the same thing on all DOM elements. If we want to do different operations on each DOM, we need to iterate over it ourselves. JQuery provides two methods for traversal, including:

  • $('selector').each(function(index, domEle) {})Iterate over the selected DOM element
  • $.each(object, function(key, value) {})You can iterate through any object, including JQuery objects, arrays, and normal objects

Let’s take an example:

  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <script>
      let color = ['red'.'green'.'blue'];
      let fontSize = ['20px'.'30px'.'40px'];
      $('ul li').each(function (index, domEle) {
        $(domEle).css('color', color[index]);
      });
      $.each($('ul li'), function (index, domEle) {
        $(domEle).css('fontSize', fontSize[index]);
      });
      $.each([1.2.3].function (index, value) {
        console.log(index, value);
      });
      $.each({ name: 'zhangsan'.age: 20 }, function (key, value) {
        console.log(key, value);
      });
    </script>
  </body>
Copy the code

Create add delete elements

In the native DOM, we create elements using document.createElement() and add them to the DOM tree using appendChild(). JQuery is similar, but much simpler, and provides the following apis:

  • $('<div> new element </div>')To create an element, you simply pass in the tag string, which can be nested in multiple layers, such as$(<div><span> new </span></div>)Nest one more layerspanThat’s ok.
  • $('selector').append(el)Adds the element to the inner end
  • $('selector').prepend(el)Adds the element to the inner beginning
  • $('selector').after(el)Appends the element to the selected element
  • $('selector').before(el)Appends the element before the selected element
  • $('selector').remove()Delete selected elements
  • $('selector').empty()Deletes all children of the selected element
  • $('selector').html("")Remove all children of the selected element, as in empty()

Let’s take an example:

  <body>
    <div class="container">
      <div>inner current element</div>
    </div>
    <div class="trash">
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
    <div class="footer">footer</div>
    <script>
      let first = $('<div>inner first element</div>');
      let last = $('<div>inner last element</div>');
      let before = $('<div>outer before element</div>');
      let after = $('<div>outer after element</div>');
      $('.container').append(last);
      $('.container').prepend(first);
      $('.container').after(after);
      $('.container').before(before);
      $('.trash').empty();
      $('.footer').remove();
    </script>
  </body>
Copy the code

JQuery event operations

The binding event

In the native DOM, there are generally two methods for event binding. One is through the onxxx property of the DOM object, and the other is through the dom.addeventListener () method. JQuery packages more convenient apis based on the latter, including the following:

  • $('selector').click(function(){})Defining a single event
  • $('selector').on({mouseenter: function(){}, mouseleave: function(){}})Define multiple different events
  • $('selector').on('mouseenter mouseleave', function(){})If multiple event handlers are the same, you can write event names together, separated by Spaces
  • $('selector').on('click', 'selector', function(){})Implement event delegate, for example$('ul').on('click', 'li', function(){})The event is bound toulAbove, but only if the trigger object isliElement
  • $('selector').one('click', function(){})One and ON have the same function, but are executed only once
  • $('selector').off()Remove all events
  • $('selector').off('click')Remove an event. If there are multiple events, separate them with a space
  • $('selector').off('click', 'selector')Disengagement of event delegation

Let’s take an example:

  <body>
    <div class="container">
      <button class="btn">close</button>
      <ul class="list">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
    <script>
      $('.list').on({
        mouseover: function () {
          console.log('list mouseover');
        },
        mouseout: function () {
          console.log('list mouseout'); }}); $('.btn').click(function () {$('.list').off();
        console.log('list event is closed');
      });
    </script>
  </body>

Copy the code

Triggering event

After event binding, we usually wait for the browser to catch the event before executing the function, but sometimes we want to trigger the event manually in our code. JQuery provides us with some apis, including the following:

  • $('selector').click()Triggers the corresponding event
  • $('selector').trigger('click')Triggers the specified event
  • $('selector').triggerHandler('click')Fires the specified event, but prevents the default behavior

Let’s take an example:

  <body>
    <div class="container">
      <button class="btn">button</button>
      <input type="text" />
    </div>
    <script>
      $('.btn').click(function () {
        console.log('button click');
      });
      $('input').focus(function () {$(this).val('content');
      });
      $('.btn').click();
      $('.btn').trigger('click');
      $('input').triggerHandler('focus');
    </script>
  </body>
Copy the code

The end of the

That’s all you need to know about JQuery. Although this article took a whole day to write, the process was very productive. I hope this article can help you.