jquery Version upgrade step pit Daquan _jquery

Source: Internet
Author: User
Tags deprecated jquery library

Background

--------------------------------------------------------------------------------

jquery must be familiar to every web engineer, but today many sites use a very old version of jquery. In fact, if the earlier version of the use of improper, there may be a DOMXSS vulnerability, it is recommended to upgrade to jquery 1.9.x or more versions. I've been leading this thing for a while, upgrading the jquery version of the project that our group is responsible for from 1.4.2 to jquery 1.11.3. The jquery official also provides jquery migrate plug-ins for similar upgrades.

Anyway

Where does the pit come from?

--------------------------------------------------------------------------------

jquery 1.11.3 is the last version of the 1.x era (author update: January 8, 2016, jquery 1.12.0 online, jquery 1.11.3 is no longer the last version of the 1.x ERA), because my department project has been a certain year, or the use of jquery 1.4.2, the upgrade step is relatively large. Many of the early versions of jquery have been discarded in the new version, or some of the nonstandard wording, which was supported at the time, but is now not supported. Worse still, the new version is supported, but the functionality is not what it used to be ... This situation is not even a mistake, you need to go deep into the code logic to see.

jquery has officially recommended the jquery Migrate Library to address the jquery upgrade issue. However, it is not always a long-term use of this library, the development of the proposed use of jquery migrate development version, you can print out the browser console is not compatible with the local details. It is important to note that the development version of the jquery migrate must be used in development, because the compressed version will not be given a warning in the console ... The jquery migrate library is referenced immediately after the jquery library:

<script src= "<path>/<to>/jquery-1.11.3.js" ></script>

After the upgrade is finished, make sure that there is no problem, then the jquery migrate library will be removed. According to personal experience, I put the pit into a common pit, a rare pit two categories to discuss.

Common pits

--------------------------------------------------------------------------------

1. Use of abandoned JQuery.fn.live method

The JQuery migrate library also has a corresponding warning in the console for this error:

JQMIGRATE:jQuery.fn.live () is deprecated
The live method is intended to set up the event agent, which is deprecated after jquery 1.7, instead of the JQuery.fn.on function. Their interfaces are:

$ (selector). Live (' click ', function () {/* Some code */});

At first glance, the parameters inside the brackets can be omitted, two functions are not exactly the same? So naively replaced the function name live directly on, and most of the time it didn't seem to cause any abnormalities. But if you call the on function, the preceding $ (selector) does not match any elements at all on the current Web page (the element may be the later code added to the DOM), which is not bound to succeed. In fact, the live function proxies $ (selector) to the document element, and this element is definitely there, so there is no such thing. The correct way to replace this should be:

$ (selector). Live (' click ', function () {/* Some code */}); Replaced by

2. Use of abandoned JQuery.fn.die method

The JQuery migrate warning for this error is:

JQMIGRATE:jQuery.fn.die () is deprecated

This method and the preceding live just in turn, canceling the binding of the event handler function. The off function should be used instead of the new version in a similar way.

3. The discarded JQuery.fn.toggle function is used

The JQuery migrate warning for this error is:

JQMIGRATE:jQuery.fn.toggle (handler, handler ...) is deprecated

In early jquery, there are two functions named toggle, one for controlling the display and concealment of elements, and the function of this use is still present in jquery, and the other is the discarded toggle function mentioned above, which binds at least two functions to the same element. When you click on the element, two functions are executed alternately. The functions of the two functions of the same name are far from being recommended in jquery 1.8 in order to be misleading. The alternative is to combine two functions into a if-else two section of a function, and then set a Boolean variable to control which section should be executed on each click.

4. Use of discarded Jquery.browser properties

The JQuery migrate warning for this error is:

JQMIGRATE:jQuery.browser is deprecated

In the front-end development we often have to according to different browser version to make different processing, Jquery.browser was originally through the browser useragent field to extract browser-related information. It has been deprecated in the new version, but it is recommended to use the method of feature detection and to give a MODERNIZR library as a recommendation. However, change to this library may change the cost is a bit large, if you still want to follow the jquery.browser ideas, you can go to realize it. For example, to determine whether IE browser, you can use

/msie/.test (Navigator.userAgent.toLowerCase ());

That is, you manually get the UserAgent field and make a regular expression match. Similar to other browsers, it is a regular match for navigator.useragent.

5. $ (HTML) format writing error

In the jquery migrate, any of the following three warnings are part of this error:

Jqmigrate: $ (HTML) HTML strings must start with ' < ' character
Jqmigrate: $ (HTML) HTML text after the last tag is ignored
Jqmigrate:html string cannot start with a ' # ' character

This error is quite noteworthy, because our article at the beginning of the jquery low version of the XSS vulnerability, in fact, is related to this error. In JavaScript, we often write a HTML-formatted string directly into a jquery reference, such as $ (' <div></div> '). According to the new version of jquery, this HTML-formatted string must begin with a left angle bracket (less than), and no other characters are allowed. The following types of writing are all wrong:

$ ("<div></div>"); Error, the string has a space at the beginning, not at the less than ' < '
$ ("<div></div>test"); Not standard, HTML tag after the end of the extra "test", it will be ignored
$ ("#<div></div>"); Error, beginning with well number and not behind a CSS selector

This point in the writing time to pay attention to it, in fact, it is easy to avoid. The third of these errors is more than just a warning, and jquery throws an error directly and stops the JavaScript code from continuing. The general case begins with a well number, such as $ ("#test"), which is a normal selector, but is followed by an HTML string, which can be judged by jquery as a potential XSS attack.

6. JQuery.fn.attr Method Error Use (this is a very easy to make mistakes!) )

In the jQuery migrate, the warnings about the attr method are as follows:

JQMIGRATE:jQuery.fn.attr (' value ', Val) no longer sets properties
JQMIGRATE:jQuery.fn.attr (' value ') no longer gets properties
JQMIGRATE:jQuery.fn.attr (' checked ') may use property instead of attribute
JQMIGRATE:jQuery.fn.attr (props, pass) is deprecated

In practice, I found that in the early written code, get an input input form of the value, how to get it? $ (' input '). attr (' value '); How is it set up? $ (' input '). attr (' value ', ' HelloWorld '). This is not true in the new version! The right approach should be

$ (' input '). Val (); Get the value that the input form is now entering
$ (' input '). Val (' HelloWorld '); Set the value entered in the input form

Whether to get or set depends only on whether the Val method is invoked with parameters.

If you want to manually set the radio box (for example, <input type= "Radio" >) is selected, how should you set it? The old code might see this $ (' input '). attr (' checked ', true) or $ (' input '). attr (' checked ', ' checked '). These are not right now! The right approach should be

$ (' input '). Prop (' checked ', true); Set the Radio box to a selected state
$ (' input '). Prop (' checked '); Gets whether a radio box is selected, returns TRUE or False

This is the writing that starts with the jquery 1.6 version. If you set the disabled and selected properties, you also use the Prop method. So when are we going to use the attr method? The difference is that prop sets the intrinsic attributes of an element, and attr sets the custom attributes written on the HTML tag. As an example:

<input type= "checkbox" checked= "checked" haha= "Hello" >
var v1 = $ (' input '). Prop ("checked");//Return to True/false, is selected and changes to the status change the
var v2 = $ (' input '). attr ("checked");//Return "checked", which you set on the label, will not change
var v3 = $ (' input '). attr (" Haha "); Return "Hello", custom properties

The fourth error mentioned above, jQuery.fn.attr (props, pass) is deprecated this warning has never been seen in real projects, looked at the source code, triggering the warning is rarely seen in jQuery, can be ignored.

7. Illegal parameters were passed to the $.parsejson

In the jquery migrate, this error produces the following warning

JQMIGRATE:jQuery.parseJSON requires a valid JSON string

jquery changed this interface to align with the browser's Json.parse interface, starting with jquery 1.9. This problem is common when Ajax receives service-side return values. The server side may return an empty string, and calling the interface generates an error. You must pass in a valid JSON string to $.parsejson. The correction method is as follows:

var v1 = $.parsejson (str); Replaced by

8. The discarded ' hover ' event string was used

This error produces the following warning in the jquery migrate

Jqmigrate: ' hover ' pseudo-event is deprecated, use ' MouseEnter mouseleave '

When registering an event-handling function, ' hover ' can previously be considered a nickname for the ' MouseEnter MouseLeave ' two events. The nickname has now been removed, so please replace it with ' MouseEnter mouseleave ' in the code.

9. JQuery.fn.andSelf has been replaced and can no longer be used

This is a warning in the JQuery migrate:

JQMIGRATE:jQuery.fn.andSelf () replaced by JQuery.fn.addBack ()

Two function functions are identical and can be replaced directly.

Above, is in the jquery upgrade common problems, of course, in the Spirit of excellence, we still need to study the unusual problem is what it looks like. It is important to note that the following questions have never been encountered in my actual project, but they are not guaranteed to be in your project, only for the reference of interested program members.

Rare pits

--------------------------------------------------------------------------------

1. jquery incompatible browser's weird mode

This error is very simple to trigger, directly to the top of the HTML page <! DOCTYPE html> label is OK. The browser weird mode is designed to be compatible with the old Web page, which can be referenced in this article: links. I think the current web programmer should not be stupid enough not to write doctype, and rarely use this mode of the browser bar.

The error alerts displayed by the JQuery migrate are as follows:

2. AJAX global events must be bound to the document node

The warning in the JQuery migrate is as follows:

Jqmigrate:ajax events should be attached to Document:ajaxstart

Ajax global events in jquery include the following interfaces Ajaxstart, Ajaxstop, Ajaxsend, Ajaxcomplete, Ajaxerror, ajaxsuccess. Because these events are less used, they are also grouped in rare pits. Starting with jquery 1.9, these events can only be bound to the $ (document). The correct approach is as follows (excerpt from the jquery website):

$ ("#status"). Ajaxstart (function () {$ (this). Text ("Ajax started"); Amended to

3. The Ie6/7/8 browser does not support modifying the type attribute of the input form

This is a warning in the jquery migrate:

Jqmigrate:can ' t change the ' type ' of an input or button in IE 6/7/8

To change the type attribute of the input form, you can simply change the text box to a single marquee, to a multiple-selection box, and so on. Although I feel this is a kind of not elegant behavior, but many browsers are supported to do so, in addition to IE6/7/8. The proposal in practice is also less use this function as well.

4. Use of removed $.clean, $.event.handle, $.ATTRFN, $.fn.data (' Events '), JQuery.event.trigger properties and methods

This is a warning in the jquery migrate:

JQMIGRATE:jQuery.clean () is deprecated
JQMIGRATE:jQuery.event.handle is undocumented and deprecated
JQMIGRATE:jQuery.attrFn is deprecated
Jqmigrate:use of JQuery.fn.data (' events ') is deprecated
Jqmigrate:global events are undocumented and deprecated

If you've ever used these five interfaces in your own code, it's really an expert on the jquery source code. Since these five interfaces have never appeared in the official jquery document, and some have been removed in subsequent versions, there is no trace of it. Looking at the source code has the opportunity to find their presence in earlier versions, but it is not recommended. It is recommended that other methods be used to implement the corresponding functions. What the? You don't know what these five functions are? That's the best, you don't need to know now ...

5. The use of outdated $.sub () method

The warning for this issue in the JQuery migrate is as follows:

JQMIGRATE:jQuery.sub () is deprecated

This interface is very simple and does not accept any parameters. It is used to create a copy of jquery. This method is no longer in use at the beginning of the jquery 1.7 version.

6. The use of outdated jQuery.fn.error methods

The warning for this issue in the JQuery migrate is as follows:

JQMIGRATE:jQuery.fn.error () is deprecated

In jquery, the error is also the same as the Click event. Registers the handler function for the event, previously $ (selector). Error (function () {}), which is now deprecated, can be replaced with $ (selector). On (' Error ', function () {}).

Sample code

--------------------------------------------------------------------------------

Since this article calls itself "XX Daquan", it should be as comprehensive as possible. In order to understand how these pits are stepped in, we finally write a section of JS code, the requirement is to use the least code, the jquery migration Library all the pits are trampled ... That is, let the jquery migration library print out all the code it can print. The final code is as follows (the blog has no way to upload attachments, can only paste code), very easy to understand. Open the index.html file and press F12 to open the console, and you'll see the magnificent console warning ^_^

<!--filename:index.html--><!--<! DOCTYPE html>-->//KENG0 Bizarre mode  


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.