Summary of new functions in jQuery 3 and new functions in jquery

Source: Internet
Author: User
Tags jquery cdn

Summary of new functions in jQuery 3 and new functions in jquery

It has been nearly ten years since jQuery shocked the entire Web, and we have been insisting on maintaining it for good reasons. JQuery provides users with DOM operations, Ajax requests, animation creation, and other friendly interfaces. In addition, unlike DOM APIs, jQuery Adopts composite pattern ). Because of this, you can call the jQuery method on a jQuery set without worrying about the number of elements contained in the Set (zero, one or more ).

With the release of jQuery 3 in the coming weeks, jQuery will reach an important milestone. JQuery 3 fixes many bugs, adds new methods, discards and removes some features, and changes the behavior of some features. In this article, I will focus on some of the biggest changes brought about by jQuery 3.

New Features (New Features)

In the following sections, I will discuss the new important features of jQuery 3.

For... Of Loop

JQuery 3 will provide the for... of loop statement, which can be used to traverse all DOM elements in a jQuery set. This new iterator is part of the ECMAScript 2015 (also known as ECMAScript6) specification. It can realize the loop of objects that can be traversed (including Array, Map, Set, and so on.

When this new iteration method is used, the value you receive each time is not a jQuery set, but a DOM element. When you perform operations on a jQuery set, this new iteration method can slightly improve your code.

To understand how this iteration method works, assume that you want to assign an ID to each input element on the page. Before jQuery 3, you can write:

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

In jQuery 3, you can write as follows:

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

$. Get () and $. post () New signatures

JQuery 3 adds a new signature for the $. get () and $. post () tool functions to make them consistent with the interface style of $. ajax. The new signature is as follows:

$. Get ([settings])
 
$. Post ([settings])

Settings is an object with many attributes. This is the same as the object provided to $. ajax. For more details, see the $. ajax () page.
The only difference between the objects passed to $. get () and $. post () is that the method attribute of the former is always ignored. The reason is: $. get () and $. both post () have a preset HTTP Method to execute Ajax requests ($. get () uses GET, while $. post ). Generally, do not use $. get () to try to send a POST request.

Consider the following code:

$.get({  url: 'https://www.audero.it',  method: 'POST' // This property is ignored});

Despite setting the method attribute, this statement still cannot send POST requests, but can only send GET requests.

Use requestAnimationFrame () for animation

All modern browsers, including Internet javaser10 and later versions, support requestAnimationFrame. JQuery 3 uses this API internally to implement animation, so as to achieve smoother and more CPU resources.

Unwrap ()

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

unwrap([selector])

With this change, you can input a string containing a selector expression and match it within the parent element. If a match exists, the child element of the match is unwrapped. Otherwise, no operation is performed.

Changed features

JQuery 3 also modified some features.

: Visible and: hidden

JQuery 3 modified the meanings of: visible and: hidden filters. As long as the element has any layout box, including those with a width and/or height of 0, the element is considered to be: visible. For example, you can use the visible filter to select the br element and the inline element without content.

Therefore, if the page is marked as follows:

<div></div><br />

Then execute 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 ()

Another important change is related to the behavior of the data () method. The adjustment is mainly to make the method conform to the Dataset API specification. JQuery 3 changed the keys of all attributes to the camper case format. To understand this change, let's take a look at the following example.

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

If you use a version earlier than jQuery 3, you can write the following code:

var $elem = $('#container'); $elem.data({  'my-property': 'hello'});console.log($elem.data());

You will get the following results on the console:

{My-property: "hello "}

In jQuery 3, you will get the following results:

{MyProperty: "hello "}

Note that in jQuery 3, the attribute name has changed to the camper format, and there is no horizontal bars (hyphens). In earlier versions, the attribute name remains in lowercase, and keep the horizontal bars (hyphens) as they are ).

Deferred object

JQuery 3 changes the behavior of the Deferred object, the predecessor of the Promise object, and improves compatibility with the Promise/A + proposal. This object and its history are very interesting. You can read the official document or read my book jQuery practice, version 3rd. This book also covers jQuery 3.

In jQuery 1.x and 2.x, if no exception is caught in the callback function passed in Deferred, the program stops running. This is not the case with the native Promise object. It throws an exception and continuously bubbles up until it reaches window. onerror (usually ). If you do not define a function to handle this error event (we usually do not), an exception message is displayed and the program is terminated.

JQuery 3 follows the native Promise object mode. Therefore, the thrown exception is considered as a rejection and thus a failure callback is executed. After completion, the entire process continues to be executed, and successful callback will be executed in the future.

To help you better understand the difference, let's look at a small example. Consider 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 (the function that throws an error) is executed. In addition, because we have not defined any event processing functions for window. onerror, the console will output the message "Uncaught Error: An error" and the program execution will be suspended.

In jQuery 3, the behavior is completely different. You will see two messages in the console: "Failure 1" and "Success 2. The exception will be processed by the first failed callback. Once the exception is processed, the following successful function will be executed.

SVG document

No jQuery version, including jQuery 3, officially supports SVG documents. However, there are actually many methods that can work normally. Some other methods, such as the method of the operation class name, have been updated in jQuery 3, so they are also applicable. Therefore, in future versions, you should be able to use methods such as addClass () and hasClass () to operate SVG documents with confidence.

Obsolete and removed methods and attributes

In addition to the improvements mentioned above, jQuery also removes and discards some features.

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

The on () method introduced by jQuery previously provides a unified access interface to replace the bind (), delegate (), and live () methods. At the same time, jQuery uses the off () method to replace the unbind (), undelegated (), and die () methods. Bind (), delegate (), unbind (), and undelegate () are not recommended in the future, but no further action is taken.

JQuery 3 has abandoned these methods and plans to remove them in a future version (possibly jQuery 4), insisting on using the on () and off () methods in the project, in this way, you don't have to worry about future version changes.

Remove the load (), unload (), and error () Methods

JQuery 3 has completely abandoned the discarded load (), unload (), and error () methods. These methods have been marked as obsolete long ago (since jQuery 1.8), but they still exist. If the plug-in you are using still relies on these methods, the code will go wrong when you upgrade to jQuery 3. Therefore, pay attention to the upgrade process.

Remove context, support, and selector

JQuery 3 has completely abandoned the obsolete context, support, and selector attributes. As mentioned above, if these attributes are still used in the project, or a plug-in is still dependent on these attributes, the code will go wrong when it is updated to jQuery 3.

Bugs repair

JQuery 3 fixed some major bugs in earlier versions. In the following sections, I will focus on two of them, because these two will have a significant impact on your encoding.

The return values of width () and height () are no longer rounded.

JQuery 3 fixes a bug in width (), height (), and other related methods. The return values of these methods are no longer rounded to pixels, because it makes it difficult to locate the elements in some cases.

To understand this problem, let us assume that you have a container element with a width of 100 pixels. This element has three sub-elements with a width of 1/3 (that is, 33.333333%:

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

In versions earlier than jQuery 3, if you try to use the following code to obtain the width of sub-elements ......

$('.container div').width();

...... The result is 33. The reason is that jQuery rounds the value 33.33333 to an integer. In jQuery 3, this Bug has been fixed and your results will be more accurate (for example, floating point numbers ).

WrapAll ()

In the new version of jQuery, The wrapAll () method bug is fixed. This bug occurs when a function is passed to the wrapAll () method. In versions earlier than jQuery 3, when a function is passed to the wrapAll () method, It wraps each element in the jQuery set separately. In other words, this behavior is exactly the same as that when a function is passed to wrap.

In addition to solving this problem, because this function is called only once in jQuery 3, the index of the element in the jQuery set cannot be passed in. Finally, the context (this) of the function points to the first element in the jQuery set.

Download jQuery 3

You can obtain files from jQuery CDN or directly access the link:

Https://code.jquery.com/jquery-3.0.0.js
Https://code.jquery.com/jquery-3.0.0.min.js
You can also obtain updates from the following npm:

npm install jquery@3.0.0

Summary

Many people say that jQuery is dead and think that there is no place in modern web development. However, jQuery development continues, and objective statistics (1 million of the top 78.5% websites) refute these claims.

In this article, I have learned about some major changes that jQuery 3 will bring. You may have noticed that this version may have a huge impact on your existing projects, because there are not many major changes introduced. However, you still need to pay attention to some factors, such as improvements to the Deferred object. As it is often necessary to update third-party dependencies, a review of the project must be performed to prevent unexpected behaviors or functional crashes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.