JQuery 1.9 upgrade Guide

Source: Internet
Author: User
Tags new set
JQuery 1.9 upgrade guide original address: http://jquery.com/upgrade-guide/1.9/ translation of the wrong or not fluent places welcome to leave a message. Overview

JQuery 1.9 deletes or modifies several APIs with inconsistent or inefficient behavior in the past. In these changes, the team's goal is to fix inconsistent jQuery behavior or difficult to use. In this process, the overall performance is improved and the file volume is reduced.

This list seems to give you some bad feelings. This is because jQuery 1.9 deletes and modifies APIs that previously have special requirements, such as jQuery. browser. How to upgrade? First, look at your code. The best way is to try the jQuery 1.9 and Migrate (Migration) plug-ins (as described below ).

JQuery Migrate (Migration) Plug-in

We realize that existing websites and plug-ins may be affected by these changes, so we provide a transitional upgrade path-jQuery Migrate (Migration) plug-in. In the following description, most of the APIS changed or deleted in 1.9 can be restored using the jQuery Migrate (Migration) plug-in. Please note that all changes in jQuery 1.9 will also be applied to jQuery 2.0. The jQuery Migrate (Migration) Plug-in is also available in jQuery2.0.

Uncompress. When the development version of The jQuery Migrate (Migration) Plug-in is used, a warning is displayed on the console, indicating in detail the incompatible or deleted information and solutions. This makes it very useful for finding and fixing problems on existing jQuery code and plug-ins. The jQuery Migrate (Migration) Plug-in has existed since 1.6.4, but 1.9 does not support all APIs.

The compressed version of The jQuery Migrate (Migration) Plug-in does not generate any incompatible or deleted information in the browser console, and can be used in jQuery 1.9 or later versions, or use the old incompatible jQuery code or plug-in.

Ideally, this can only be a short-term solution, but you have to make your own decisions.

For more information, see jQuery Migrate plugin.

Note: It is not a long term to use jQuery Migrate (Migration) plug-ins to modify incompatible code as soon as possible.

Changed in jQuery1.9

What is mentioned in the following list does not represent all changes in jQuery 1.9, but is what we expect. For a complete and detailed list of changes, see the announcements published in The jQuery blog or visit bugs.jquery.com.

. Toggle (function, function ,... ) Method Deletion

This method binds two or more handlers to matched elements to execute alternate click events. Because it is not outdated. The former is deleted to reduce confusion and improve modularity. The jQuery Migrate (Migration) Plug-in can restore this function.

Delete jQuery. browser ()

The jQuery. browser () method has expired since jQuery 1.3 and is deleted in 1.9. If necessary, the jQuery Migrate (Migration) Plug-in can restore this function. We recommend that you use the Modernizr library for feature detection.

Remove the. live () method

The. live () method has expired since jQuery 1.7 and is deleted in 1.9. We recommend that you use the. on () method to replace and upgrade your code. To fully match $ (". foo "). live ("click", fn). For example, you can write $ (document ). on ("click", ". foo ", fn) (Note: because the original live event is actually bound to the document ). During this period, you can use the jQuery Migrate (Migration) Plug-in to restore the. live () function.

Remove the. die () method

The. die () method has expired since jQuery 1.7 and is deleted in 1.9. We recommend that you use the. off () method to replace and upgrade your code. To fully match $ (". foo "). die ("click"). For example, you can write $ (document ). off ("click", ". foo "). During this period, you can use the jQuery Migrate (Migration) Plug-in to restore the. die () function.

JQuery. sub () method removed

The jQuery. sub () method is moved to the jQuery Migrate (Migration) plug-in. The frequency of use proves that it is unnecessary to stay in the core code base. This function is added to the jQuery Migrate (Migration) plug-in.

. Add () method Modification

The results returned by the. add () method are always arranged in the order of the nodes in the document. Before 1.9, if any node in the context or input collection that is separated from the document (not included in the document), use. the add () method node is not ordered by the order in the document. Now, the returned nodes are sorted in the order in the document, and the nodes that are separated from the document are placed at the end of the set.

. AddBack (selector) replace. andSelf ()

Since jQuery1.8, The. andSelf () method has been marked out. Use. addBack () in jQuery1.8 and later versions ().

We think this is a better name for the result set before "add and return. The new method can accept an optional selector, which can be used to filter the previous set, add it to the current set, and return. $ ("Section, aside "). children ("ul "). addBack ("aside") obtains all ul sub-elements under section and aside, plus all aside elements, according to their order in the document. Although. addSelf () can still be used in 1.9, we recommend that you change the name as soon as possible. If you use. addSelf (), the jQuery Migrate plug-in will warn you.

. After (),. before (), and. replaceWith () use nodes that are separated from the document

Before 1.9 ,. after (),. before (), and. replaceWith () will try to add or change nodes in the current jQuery set. If the node in the current jQuery set is not connected to the document (note: the node that is separated from the document ), in this case, a new jQuery set is returned, instead of the original set. This will generate some contradictions and complete errors-This method may or may not return a new result, depending on its parameters! Starting from 1.9, these methods always return the original unmodified set and try to use it on a node without a parent node. after (),. before (), or. replaceWith () has no effect-neither of this set or the nodes it contains is changed.

. AppendTo,. insertBefore,. insertAfter, And. replaceAll

In 1.9, these methods always return a new set so that they can use chained calls and. end () methods. Before 1.9, only when they are a separate target element will they return the old set. Note that these methods always return the aggregation set of all elements appended to the target element. If no element is selected by the target selector (for example, $ (elements). appendTo ("# not_found"), the returned set is null.

AJAX events need to be bound to the document

In jQuery 1.9, global AJAX events (ajaxStart, ajaxStop, ajaxSend, ajaxComplete, ajaxError, and ajaxSuccess) can only be triggered on the document element. Modify the AJAX event listener to the document element. For example, if the current code looks like this:

$("#status").ajaxStart(function(){ $(this).text("Ajax started"); });

Modify:

$(document).ajaxStart(function(){ $("#status").text("Ajax started"); });
. Trigger () "click" event Checkbox/radio status

When you click a check box or single-choice button, if the node does not call the event. preventDefault (), the event handler determines and obtains its new status based on the check box or the current status of one choice. Therefore, for example, if a user clicks an unselected checkbox, the event handler selects the checkbox. Before 1.9,. trigger ("click") or. click () will trigger a merging event. Based on the user's click behavior, we can see that the checkbox is in the opposite state as the actual checked attribute. Fixed this bug in 1.9, and the user behavior will get the corresponding status.

Focus event trigger sequence

When the user clicks the form element or presses the tab key to get the focus of the element, the browser first triggers a blur (no focus) event on the focus element, then, a focus event is triggered on the new element. Before 1.9, use. trigger ("focus") or. when focus () is bound to a focus event, the new element triggers a focus event and then triggers the blur event of the previous focus element. 1.9 has fixed this issue.

If the target element does not obtain the focus and the focus can be obtained successfully (for example, the disabled form element cannot obtain the focus), use the native focus event of DOM, the browser only accesses the focus event handler. JQuery always calls the handler bound to. trigger ("focus") or. focus (), regardless of whether the element gets focus. This is still the case in jQuery 1.9. Unlike the DOM's. focus () method, in many cases, the element has obtained the focus or the element is disabled, and the DOM's. focus () method does not call the event handler.

Unfortunately, all versions of Internet Explorer (6-10) trigger focus events asynchronously. When you use. trigger ("focus") in IE, jQuery cannot "predict" what will happen after the asynchronous focus event. Therefore, it will always trigger a focus event to ensure normal functionality. This may cause the focus event to be re-executed. We recommend that you use the DOM built-in focus (), for example, $ ("# boo"). get (0). focus ().

JQuery (htmlString) and jQuery (selectorString)

Before 1.9, if a string contains any HTML Tag, the string will be considered as an HTML string. This may cause unexpected code execution and rejection of valid selector strings. Starting from 1.9, a string starting with a character smaller than the sign ("<") is considered an HTML string. The Migrate (latency) Plug-in can restore the behavior before 1.9.

If a string is considered HTML, but it may start with any text that is not an HTML Tag, passing it to jQuery. parseHTML () will return the tag represented by a DOM node array. We can use it to create a jQuery set, for example, $ ($. parseHTML (htmlString )). For example, this is considered a best practice for processing HTML templates. Simple use of text strings, such as $ ("<p> Testing </p>"). appendTo ("body") will not be affected.

In short, when an HTML string is passed to jQuery (), all strings except starting with a character smaller than the sign ("<") will be interpreted as a selector. Because a string cannot be interpreted as a selector, the most likely result is the "invalid selector Syntax" thrown by the Sizzle selector engine error ". Use jQuery. parseHTML () to parse arbitrary HTML.

Using the jQuery Migrate (Migration) plug-in, if the string is passed to $ () and "looks like HTML", it will be determined using the old rules.

The. data () name contains vertex (".") changed

. Data () has an undisclosed and incredible set and acquisition of non-high-performance metric values, and is removed from 1.9. This has affected the parsing of Data names that contain vertices. Starting from 1.9, calling. data ("abc. def") can only retrieve data by name "abc. def". The technique that can be obtained through "abc" has been canceled. It should be noted that the lower-level jQuery. data () method does not support events, so it has not changed. Even with the jQuery Migrate (Migration) plug-in, the original behavior cannot be restored.

Separated from the order of document nodes in the jQuery set

For many versions, almost all jQuery Methods return a new set of nodes, which is a result set that uses their sequential sorting in the document. (There are several methods, such as. parents () returned results are sorted in reverse order in the document, but these exceptions have not changed in 1.9 .)

Before 1.9, Unexpected random sorting may occur if the nodes of the mixed DOM in the jQuery set and the nodes that are not included in the DOM are separated from the document node. Starting from 1.9, the connection nodes in the document are always placed at the beginning of the Set in the document order, and the separation nodes are placed behind them. Even with the jQuery Migrate (Migration) plug-in, the original behavior cannot be restored.

Load and execute scripts in HTML content

Before 1.9, any method that accepts HTML strings (for example, $ (),. append (),. wrap () executes the scripts contained in the HTML string and removes them from the document to prevent them from being executed again. In special cases, a script using these methods may be removed and re-inserted into the document, such as. wrap (). Starting from 1.9, scripts inserted into the document will be executed, but they will still be kept in the document and marked as executed, so that they will not be executed again, even if they are deleted and re-inserted.

Despite this change, mixing executable JavaScript in HTML tags is a bad habit; it affects design, security, reliability, and performance. For example, it may take a lot of time for external script tags to be retrieved synchronously in HTML and then evaluated and executed. There is no interface to notify these scripts of when and where to load, or receive a correction prompt when an error occurs.

An attempt to clone an existing script tag to load and inject the script will no longer work because the cloned script tag has been marked as executed. To load a new script, we recommend that you use jQuery. getScript () instead.

Comparison Between. attr () and. prop ()

JQuery 1.6 introduces how to set the. prop () method or obtain the object property on a node. It is not recommended to use the. attr () method to set the object property ). However, the. attr () method is still supported in some special cases until version 1.9. When a selector is used to distinguish between a tag attribute (attributes) and an object attribute (properties), such behavior can cause confusion in backward compatible naming.

For example, the Boolean tag attribute (attributes) of a check box, for example, checked and disabled are affected by this change ." The correct action of input [checked] "is to select the check box with the checked attribute, whether it is its string value or its current status. In contrast, "input: checked" selects the check box where the Boolean value (true or false) of the current checked attribute is true. For example, when you click the check box, the check box will be affected. Those selectors earlier than version 1.9 sometimes do not select the correct node.

Here are some examples. When a checked attribute is set on the check box, the correct and incorrect usage is correct. The same rule applies to the disabled attribute. Note that only the object property is in the current status of the check box that is always reflected and updated in all browsers; you rarely need to set the attribute ).

// Correct if changing the attribute is desired$(elem).attr("checked", "checked");// Correct for checking the checkbox$(elem).prop("checked", true);// Correct if removing the attribute is desired$(elem).removeAttr("checked");// Correct for clearing the checkbox$(elem).prop("checked", false);

The property and attribute of the input element are another examples of this ambiguity. Attribute generally indicates the value of the HTML Tag. The attribute reflects the current value. Because the. val () method is recommended by jQuery to obtain or set the values of form elements, such obfuscation usually does not affect users.

However, when a selector such as "input [value = abc]" is used, it should always select the value tag attribute and) there is no change, for example, from these selectors to a text input box. This behavior is correct and consistent from jQuery 1.9. In earlier jQuery versions, tag attributes are sometimes used ).

The jQuery Migrate (Migration) Plug-in can restore the original property and attribute rules.

$ ("Input"). attr ("type", newValue) in old IE)

Before version 1.9, in all browsers, jQuery will throw an exception for any attempt to set the type (type attribute) of an input or button element. This is done to ensure compatibility with the lowest standards; because if you try to change the type of the input element, IE6/7/8 throws an error. From jQuery 1.9, if the browser permits, we allow you to set the element type. However, you need to know your own code. If you try to do this in Internet Explorer (IE6/7/8), an error will still be thrown. When you try to set the type attribute, the jQuery Migrate (Migration) Plug-in will issue a warning, but will not throw a JavaScript error.

"Hover" pseudo event

From 1.9, the event name string "hover" no longer supports the abbreviation of "mouseenter mouseleave. Allows applications to bind and trigger custom "hover" events. Modifying the existing code is a simple search/replacement, and the jQuery Migrate (latency) Plug-in can restore the "hover" pseudo event.

The. selector attribute on the jQuery object

The obsolete selector attribute on the jQuery object is retained to support outdated. live () events. In 1.9, jQuery no longer tries to keep this attribute on the chain method, because 1.9 has removed the. live () event. Do not use the. selector attribute of the jQuery object. The jQuery Migrate (Migration) Plug-in does not support this attribute either.

JQuery. attr ()

Version 1.9 removes the jQuery. attr (elem, name, value, pass) method, which can be restored using the jQuery Migrate (Migration) plug-in.

JQuery. ajax returns the JSON result of an empty string.

Before 1.9, an AJAX call is expected to return the Data Type of JSON or JSONP. When the returned value is an empty string, it is considered successful, however, a null value is returned to the success handler or promise (promise ). Starting from 1.9, JSON data returns an empty string that is considered to be malformed JSON (because it is originally); this will throw an error. In this case, the error handler is used to capture.

JQuery. proxy ()

Before version 1.9, $. proxy (null, fn), $. this of proxy (undefined, fn) will point to window, and $. this of proxy (false, fn) points to new Boolean (false); from 1.9 onwards, if the context is passed in null/undefined/false, this of the function will maintain the original context and will not be changed.

. Data ("events ")

Before 1.9, if no other Code defines a data element named "events ,. data ("events") can be used to retrieve internal event data structures that are not disclosed by jQuery on an element. This special case has been deleted in 1.9. There is no public interface to obtain this internal data structure,

It is not public. The jQuery Migrate (Migration) Plug-in can restore the original behavior.

Remove some properties of the Event object

The attrChange, attrName, realtedNote, and srcElement attributes of Event objects are declared obsolete because they cannot be transferred across browsers. Since jQuery 1.7, they are no longer copied to Event objects and passed to Event handlers. In all jQuery versions, these attributes can still be accessed through event. orginalEvent on browsers that support them to replace event. The jQuery Migrate (Migration) Plug-In adds these attributes to the Event object.

Parameters not publicly available for API methods

Before 1.9, several API methods did not publicly change their behavior parameters, and there was potential accidental misuse. These parameters have been deleted. Affected methods include jQuery. data (), jQuery. removeData (), and jQuery. attr (). The code that is not supported by the jQuery Migrate (Migration) plug-in.

Other undisclosed attributes and Methods

The following internal attributes and methods have never been included in the document and are deleted in section 1.9.

  • JQuery. deletedIds
  • JQuery. uuid
  • JQuery. attrFn
  • JQuery. clean ()
  • JQuery. event. handle ()
  • JQuery. offset. bodyOffset ()

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.