Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What's new with jQuery 3.0? (The most important changes introduced by jQuery 3)


May 07, 2021 jQuery


Table of contents


It's been ten years since jQuery came out of the sky, and its perennity is clearly not without reason. j Query provides an extremely friendly interface that makes it easy for developers to do DOM operations, initiate Ajax requests, generate animations... I t's not the same. I n addition, unlike the DOM API, jQuery uses a "hybrid mode." T his means that you can call the jQuery method on any jQuery collection without having to worry about how many elements it contains (zero, one or more, no problem).

jQuery 3 fixes a large number of bugs, adds new methods, removes some interfaces, and modifies the behavior of a small number of interfaces.

What's new

Let's start by discussing some of the most important new features in jQuery 3.

for...of Loop

for...of loop

In jQuery 3, we can use for...of loop statements to iterate all DOM elements in a jQuery collection. T his new iterative approach is part of the ECMAScript 2015 (i.e. ES6) specification. T his method loops through "iterative objects" such as Array Map Map, Set and so on.

When using this new iterative method, the value you get each time in the loop body is not a jQuery object, but a DOM element .each() method). T his new iterative approach can improve your code a little while you're working on a jQuery collection.

To figure out exactly how this iterative approach works, let's assume a scenario where you need to input to each input element on the page. Before jQuery 3, you might have written this:

var $inputs = $('input');

for(var i = 0; i < $inputs.length; i++) {
   $inputs[i].id = 'input-' + i;
}

And in jQuery 3, you can write this:

var $inputs = $('input');
var i = 0; 

for(var input of $inputs) {
   input.id = 'input-' + i++;
}

$.get() $.post() functions

jQuery 3 $.get() $.post() tool functions, making them consistent with the interface style of $.ajax() The new signature is something like this:

$.get([settings])

$.post([settings])

settings is an object that contains multiple properties. I t has the same format as the $.ajax() I f you want to get a clearer picture of this parameter object, $.ajax() page.

The only difference between $.post() is that the method property of the former is always ignored compared to the method $.get() $.ajax() T he reason is simple: $.get() and $.post() themselves already preset the HTTP method for initiating Ajax requests $.get() is GET, $.post() is POST). T hat is, normal humans should not want to send a POST request using the $.get() method.

Suppose you have the following piece of code:

$.get({
	url: 'http://www.w3cschool.cn',
	method: 'POST'  // 这个属性将被忽略
});

No matter what method about the method property, the request is always sent as GET.

Use of requestAnimationFrame() for Animations

Use requestAnimationFrame() implement animation

All modern browsers, including IE10 and above, requestAnimationFrame jQuery 3 will use this API internally for animation for smoother, more resource-efficient animation.

unwrap() method

jQuery 3 adds an optional selector parameter to the unwrap() method. The new signature for this method is this:

unwrap([selector])
With this attribute, you can pass in a string to this method, which is a selector expression that matches the parent element of the current element. If matched, the parent element layer is stripped;

There are changeable features

jQuery 3 also modifies the behavior of some features.
:visible and :hidden

jQuery 3 will modify the meaning of the :visible :hidden filters. A s long as the element has any layout box, even if it is zero in width, it is considered :visible F or example, br element and the in-row element that do not contain the content are now selected :visible filter.

Therefore, if your page contains the following structure:

<div></div>
<br />

Then run the following statement:

console.log($('body :visible').length);

In jQuery 1.x and 2.x, you get 0 but in jQuery 3, you get 2

data() method

Another important change is related to data() method. N ow its behavior has become consistent with the Dataset API specification. j Query 3 converts all property key names into hump form. Let's take a look at the following elements in detail:

<div id="container"></div>

When we're using a previous version of jQuery 3, if you run the following code:

var $elem = $('#container');

$elem.data({
   'my-property': 'hello'
});

console.log($elem.data());
You'll get the following results in the console:
{my-property: "hello"}
In jQuery 3, we'll get the following results:
{myProperty: "hello"}
Note that in jQuery 3, the property name has become a hump, the bar has been removed, and in previous versions, the property name remains fully undercase and the bar is preserved as is.

Deferred object

jQuery 3 also changes the behavior Deferred object. /b12> Deferred is arguably one of the predecessors of the Promise object and is compatible with the Promise/A-plus protocol. T his object and its history are quite interesting. If you want to learn more, you can read jQuery's official documentation

Or

jQuery Battle (Third Edition) - This book also covers jQuery 3.

In jQuery 1.x and 2.x, Deferred immediately interrupts the execution of the program (i.e., silent failure, which is true of the behavior of the vast majority of jQuery callback functions). T his is not the case with the native Promise object, which throws an exception and continues to bubble upward window.onerror (usually the end point of the bubble is here). I f you don't define a function to handle this error event (which we don't usually do), the information about the exception will be displayed and the execution of the program will stop.

jQuery 3 will follow the pattern of the native Promise object. T herefore, an exception generated within the callback causes a failure state and triggers a failed callback. O nce the failed callback is executed, the entire process will continue and subsequent successful callbacks will be executed.

To give you a better understanding of this difference, let's look at a small example. For example, we have the following code:

var deferred = $.Deferred();

deferred
  .then(function() {
    throw new Error('An error');
  })
  .then(
    function() {
      console.log('Success 1');
    },
    function() {
      console.log('Failure 1');
    }
  )
  .then(
    function() {
      console.log('Success 2');
    },
    function() {
      console.log('Failure 2');
    }
  );

deferred.resolve();

In jQuery 1.x and 2.x, only the first function (that is, the one that throws the error) is executed. I n addition, since we do not define any event window.onerror the console outputs "Uncaught Error: An error" and the execution of the program is aborted.

In jQuery 3, the whole behavior is completely different. Y ou'll see "Failure 1" and "Success 2" messages in the console. The exception will be handled by the first failed callback, and once the exception is handled, subsequent successful callbacks will be called.

SVG documentation

No jQuery version, including jQuery 3, has officially declared support for SVG documentation. I n fact, however, there are a number of methods that work, and there are methods that were not previously possible (such as those that manipulate class names), but they have also been updated in jQuery 3. T herefore, in jQuery 3, you should be addClass() such hasClass() to manipulate SVG documents. SVG

Discarded, removed methods and properties

In addition to these improvements, jQuery has removed and discarded some features.

Discard bind() unbind() delegate() and undelegate()

jQuery introduced the on() method a long time ago, which provides a unified interface to replace methods such bind() delegate() live() A t the same time, jQuery introduced off() instead of unbind() undelegated() die() S ince then, bind() , delegate() unbind() undelegate() to be recommended, but they still exist.


jQuery 3 is finally starting to mark these methods as "obsolete" and plans to remove them completely in a future release, most likely jQuery 4. T herefore, use the on() and on() uniformly off() that you don't have to worry about future version changes.

Remove load() unload() error()

jQuery 3 completely discards methods load() unload() error() that have been marked as obsolete. T hese methods have been marked as obsolete for a long time (starting with jQuery 1.8), but have not been removed. I f the plug-in you're using still relies on these methods, upgrading to jQuery 3 will hang up your code. T herefore, be careful during the upgrade process.

Remove context support selector

jQuery 3 completely discards context been marked selector such as support and selector. S imilarly, when upgrading to jQuery 3, keep an eye out for the plug-in you're using.

The bug that was fixed

jQuery 3 fixes some very important bugs from previous releases. In this section, I'll focus on two of them, because they should have a significant impact on your code writing habits.

width() of height() are no longer rounded

jQuery 3 fixes a width() height() and other related methods. T he return values of these methods are no longer rounded because this rounding behavior is not easy to locate elements in some cases.


Let's take a look at it in detail. Suppose you have a container element 100px which contains three child elements, all one-third wide (i.e. 33.333333%):

<div class="container">
   <div>My name</div>
   <div>is</div>
   <div>Aurelio De Rosa</div>
</div>

In previous versions of jQuery 3, if you tried to get the width of the child element by the following code

$('.container div').width();
Then you get the result that 33 . T he reason is that jQuery rounds the value of 33.33333. In jQuery 3, the bug has been fixed, so you'll get more accurate results (i.e., a float).

wrapAll() method

jQuery 3 also fixes a bug in the wrapAll() method that occurs when a function is passed to it as an argument. I n previous versions of jQuery 3, when a function was wrapAll() it wrapped each element in the jQuery collection individually. I n other words, this behavior is exactly the same as when you pass a function to wrap()

While fixing this problem, another change was introduced: since the function is called only once in jQuery 3, it is not possible to pass on every element of the jQuery collection to it. T herefore, the execution context (this) this this function will only point to the first element in the current jQuery collection.

How to download jQuery 3

http://jquery.com/download/


Conclusion

Many people have been singing jQuery, saying it has no place in modern web development. But in any case, jQuery's development continues, and objective statistics (78.5 percent of the top 1 million sites) make these arguments unsoppable.

In this article, I've taken you through some of the major changes that jQuery 3 will bring. A s you may have noticed, this version is unlikely to engage with your existing project, as it introduces very few disruptive changes. H owever, as you upgrade to jQuery 3, it's important to keep in mind some key points, such as Deferred and so on. S imilarly, when upgrading a third-party library, it is necessary to check the compatibility of the project in order to detect any unexpected behavior as early as possible and avoid some functional failures.

Read about it

SVG tutorial