May 07, 2021 jQuery
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.
Let's start by discussing some of the most important new features in jQuery 3.
for...of
Loop
for...of
loop
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.
requestAnimationFrame()
for Animations
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])
: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);
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());
{my-property: "hello"}
{myProperty: "hello"}
Deferred
object
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();
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.
addClass()
such
hasClass()
to manipulate SVG documents.
SVG
bind()
unbind()
delegate()
and
undelegate()
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.
load()
unload()
error()
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.
context
support
selector
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.
width()
of
height()
are no longer rounded
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();
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
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.
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.