Home Web Front-end JS Tutorial What are the new features of the upcoming jQuery 3_jquery

What are the new features of the upcoming jQuery 3_jquery

May 16, 2016 pm 03:05 PM
3 jquery new features

It has been ten years since jQuery was born, and its longevity is obviously not without reason. jQuery is another excellent Javascript library after prototype. It is a lightweight js library that is compatible with CSS3 and various browsers (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+). jQuery2.0 and subsequent versions will no longer support IE6/7 /8 browser. jQuery enables users to more easily process HTML (an application under Standard Universal Markup Language), events, implement animation effects, and easily provide AJAX interaction for websites. Another big advantage of jQuery is that its documentation is very complete and its various applications are explained in detail. There are also many mature plug-ins to choose from.

In the next few weeks, jQuery will reach an important milestone - the official release of version 3.0. jQuery 3 fixed a large number of bugs, added new methods, removed some interfaces, and modified the behavior of a small number of interfaces. In this article, I will highlight the most important changes introduced by jQuery 3.

New features

Let’s first discuss the most important new features in jQuery 3.

for...of loop

In jQuery 3, we can use the for...of loop statement to iterate all DOM elements in a jQuery collection. This new iterative approach is part of the ECMAScript 2015 (aka ES6) specification. This method can loop over "iterable objects" (such as Array, Map, Set, etc.).

When using this new iteration method, the value you get each time in the loop body is not a jQuery object, but a DOM element (Translation: This is similar to the .each() method). This new iteration method can slightly improve your code when you're operating on a jQuery collection.

To understand how this iteration method works, let’s assume a scenario - you need to assign an ID to each input element in the page. Before jQuery 3, you might write:

Copy code The code is as follows:
var $inputs = $('input');for(var i = 0; i < $inputs.length; i++) {
$inputs[i].id = 'input-' + i;
}

In jQuery 3, you can write like this:

Copy code The code is as follows:
var $inputs = $('input');var i = 0 ;
for(var input of $inputs) {
input.id = 'input-' + i++;
}

(Annotation: In fact, jQuery itself has a .each() method, which is not bad at readability.)

New signatures for $.get() and $.post() functions

jQuery 3 adds new signatures to the two utility functions $.get() and $.post(), making them consistent with the interface style of $.ajax(). The new signature looks like this:

Copy code The code is as follows:
$.get([settings])
$.post([settings])

settings is an object that contains multiple properties. Its format is the same as the parameter format you passed to $.ajax() before. If you want to understand this parameter object more clearly, please refer to the related description on the $.ajax() page.

The only difference between the parameter objects of $.get() and $.post() and the parameters passed to $.ajax() is that the method attribute of the former is always ignored. The reason is actually very simple. $.get() and $.post() themselves already preset the HTTP method for initiating Ajax requests (obviously $.get() is GET, and $.post() is POST). In other words, normal humans would not want to use the $.get() method to send a POST request.

Suppose there is the following piece of code:

Copy code The code is as follows:
$.get({
URL: 'https://www.audero.it',
Method: 'POST' // This property is ignored
                                                                                                                                                                                                                               // This attribute will be ignored});

No matter what we write the method attribute as, this request will always be sent as GET.

Use requestAnimationFrame() to implement animation

All modern browsers (including IE10 and above) support requestAnimationFrame. jQuery 3 will use this API internally to implement animations to achieve smoother, more resource-efficient animation effects.

unwrap() method

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

Copy code The code is as follows:
unwrap([selector])

With this feature, you can pass this method a string containing a selector expression and use it to match within the parent element. If there is a matching child element, the parent layer of this child element will be lifted; if there is no match, no operation will be performed.

Changed features

jQuery 3 also changes the behavior of some features.

:visible and :hidden

jQuery 3 will change the meaning of :visible and :hidden filters. As long as the element has any layout box, even if the width and height are zero, it will be considered :visible. For example, br elements and inline elements without content are now selected by the :visible filter.

So if your page contains the following structure:

Copy code The code is as follows:

Then run the following statement:

Copy code The code is as follows:
console.log($('body :visible').length) ;

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

data() method

Another important change is related to the data() method. Its behavior is now consistent with the Dataset API specification. jQuery 3 will convert all property key names to camelCase. Let’s take a closer look, taking the following element as an example:

Copy code The code is as follows:

When we are using versions prior to jQuery 3, if we run the following code:

Copy code The code is as follows:
var $elem = $('#container');
$elem.data({ 'my-property': 'hello'});console.log($elem.data());

You will get the following results in the console:

Copy code The code is as follows:
{my-property: "hello"}

In jQuery 3, we will get the following results:

Copy code The code is as follows:
{myProperty: "hello"}

Please note that in jQuery 3, attribute names have become camelCase and the dashes have been removed; whereas in previous versions, attribute names would remain all lowercase and retain the dashes as they are.

Deferred object

jQuery 3 also changes the behavior of Deferred objects. The Deferred object can be said to be one of the predecessors of the Promise object, and it implements compatibility with the Promise/A+ protocol. This object and its history are quite interesting. If you want to learn more, you can read the official jQuery documentation, or you can read my book "jQuery in Practice (Third Edition)" - this book also covers jQuery 3.

In jQuery 1.x and 2.x, if an uncaught exception occurs in the callback function passed to Deferred, the execution of the program will be interrupted immediately (Annotation: Fail silently, in fact, the behavior of most callback functions in jQuery are all like this). This is not the case with native Promise objects. It will throw an exception and keep bubbling upward until it reaches window.onerror (usually the end point of bubbling is here). If you do not define a function to handle this error event (usually we do not do this), then the exception information will be displayed, and then the execution of the program will stop.

jQuery 3 will follow the pattern of native Promise objects. Therefore, exceptions generated within the callback will cause a failure status (rejection) and trigger the failure callback. Once the failure callback is executed, the entire process will continue to advance, and subsequent success 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:

Copy code The code is as follows:
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 (the one that throws the error) will be executed. In addition, since we have not defined any event handler for window.onerror, the console will output "Uncaught Error: An error" and the execution of the program will abort.

In jQuery 3, the entire behavior is completely different. You will see "Failure 1" and "Success 2" messages in the console. That exception will be handled by the first failure callback, and, once the exception is handled, subsequent success callbacks will be called.

SVG Document

No version of jQuery (including jQuery 3) has ever officially claimed to support SVG documents. In fact, there are many methods that will work, and there are also some methods that did not work before (such as those for manipulating class names), but they have also been updated in jQuery 3. Therefore, in jQuery 3, you should be able to safely use methods such as addClass() and hasClass() to manipulate SVG documents.

Deprecated, removed methods and properties

While adding the above improvements, jQuery has also removed and deprecated some features.

Deprecated bind(), unbind(), delegate() and undelegate() methods

jQuery introduced the on() method a long time ago, which provides a unified interface to replace methods such as bind(), delegate() and live(). At the same time, jQuery also introduced the off() method to replace unbind(), undelegated() and die(). Since then, bind(), delegate(), unbind(), and undelegate() have been deprecated, but they still exist.

jQuery 3 finally starts marking these methods as "deprecated", with plans to remove them completely in some future version (most likely jQuery 4). Therefore, please use on() and off() methods uniformly in your project so that you don't have to worry about changes in future versions.

Remove load(), unload() and error() methods

jQuery 3 completely abandons load(), unload() and error() methods that have been marked as deprecated. These methods were marked deprecated a long time ago (as of jQuery 1.8) but have not been removed. If you are using a plugin that still relies on these methods, upgrading to jQuery 3 will break your code. Therefore, please pay attention during the upgrade process.

Remove context, support and selector attributes

jQuery 3 completely abandons the attributes such as context, support and selector that have been marked as deprecated. As above, when upgrading to jQuery 3, please be aware of the plugins you are using.

Bugs fixed

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

The return values ​​of width() and height() will no longer be rounded

jQuery 3 fixes a bug in width(), height() and other related methods. The return values ​​of these methods will no longer be rounded, as this rounding behavior makes positioning elements inconvenient in some cases.

Let’s take a look in detail. Suppose you have a container element with a width of 100px. It contains three child elements, and the width is one-third (ie 33.333333%):

Copy code The code is as follows:

My name

is

Aurelio De Rosa

In versions prior to jQuery 3, if you try to get the width of a child element via the following code...

Copy code The code is as follows:
$('.container div').width();

…then the result you get will be 33. The reason is that jQuery will round the value 33.33333. In jQuery 3, this bug has been fixed, so you will get a more precise result (i.e. a floating point number).

wrapAll() method

jQuery 3 also fixes a bug in the wrapAll() method that occurred when a function was passed to it as a parameter. In versions prior to jQuery 3, when a function was passed to the wrapAll() method, it would individually wrap each element in the jQuery collection. In other words, the behavior is exactly the same as when passing a function to wrap().

While fixing this problem, another change was also introduced: Since in jQuery 3, this function is only called once, it is impossible to pass every element in the jQuery collection to it. Therefore, the execution context of this function (this) will only point to the first element in the current jQuery collection.

How to download jQuery 3 beta 1

Now that you’ve read this far, you probably want to try out the first beta of jQuery 3. You can get this version through the following two addresses:

Uncompressed version: https://code.jquery.com/jquery-3.0.0-beta1.js

Compressed version: https://code.jquery.com/jquery-3.0.0-beta1.min.js

Of course, you can also download it through npm:

[code]npm install jquery@3.0.0-beta1[/code]

Conclusion

Many people have been badmouthing jQuery, saying that it has no place in modern web development. But regardless, jQuery development continues, and objective statistics (a share of 78.5% of the top one million websites) undermine these arguments.

In this article, I have taken you through some of the major changes that jQuery 3 will bring. As you may have noticed, this version is unlikely to break your existing projects because it introduces very few breaking changes. However, when upgrading to jQuery 3, you still need to keep some key points in mind, such as the improvements to Deferred objects and so on. Similarly, when upgrading a third-party library, it is also necessary to check the compatibility of the project in order to detect any unexpected behavior as early as possible and avoid the failure of certain functions.

Translation Note

In addition to the changes mentioned in this article, the biggest change in jQuery 3.0 is the complete abandonment of support for IE8. The reason why the jQuery team made this decision is that Microsoft announced at the beginning of this year that it would stop supporting IE 8~10. Therefore, there is no need for the jQuery Compat project released in the 3.0 alpha phase of jQuery to continue to exist.

However, since IE8 is still one of the most popular browsers in mainland China, domestic developers will have to stay at the jQuery 1.x version in the short (or even medium) term.

Okay, let’s finally tell you the good news. To help users upgrade smoothly, jQuery will also provide a migration plugin (jQuery Migrate plugin) for version 3.0 this time. After upgrading jQuery to 3.0, run this plug-in at the same time to ensure that the existing business code based on jQuery 1.x or 2.x runs normally; at the same time, it will also report to you in the console that the existing code is different from jQuery 3. Compatible places. Once you have fixed these incompatibilities, it is safe to remove the plugin.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles