jquery Upgrade trample Pit Daquan

Source: Internet
Author: User
Tags deprecated jquery library

  

background

jquery must be familiar to every web engineer, but today many websites use a very old version of jquery. In fact, if the earlier version of improper use, there may be domxss vulnerabilities, it is recommended to upgrade to jquery 1.9.x or later. I dominated this matter a while ago and upgraded the jquery version of our group of projects from 1.4.2 to jquery 1.11.3. jquery also officially provides a jquery migrate plugin for similar upgrade efforts.

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, then the use of the jquery 1.4.2, this upgrade step is relatively large. In the early days, many of jquery's writing had been deprecated in the new version, or had some irregular wording, which was supported by the version, but is now unsupported. Worse still, the new version is supported, but the functionality is not the same as before ... This situation is not reported in a wrong way, and needs to go deep into the code logic to see.

jquery has officially recommended the jquery Migrate library to solve the jquery escalation problem. However, the use of this library is not a long-term long-term development, it is recommended that the development of jquery migrate, can be printed on the browser console incompatible details of the place. It is important to note that the development of jquery migrate must be used in development because the compressed version is not given a warning in the console ... Keep the jquery migrate library immediately behind the jquery library by referencing it:

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

After the upgrade is complete, OK no problem, then the jquery migrate library to remove it. According to personal experience, below I divide the pit into common pit, rare pit two kinds to discuss.

  Common Pits 1. The deprecated JQuery.fn.live method is used

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

JQMIGRATE:jQuery.fn.live () is deprecated

The original role of the live method is to set up the event proxy, which is deprecated after jQuery1.7, and replaces it with the JQuery.fn.on function. Their interfaces are:

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

At first glance, the parameters inside the brackets can be omitted, the two functions are not identical? So naïve to replace the function name live directly to ON, most of the time, this does not seem to cause any abnormalities. However, if you call the on function, the previous $ (selector) does not match any element at all on the current page (the element may be appended to the DOM), it will not be bound successfully. In fact, the live function proxies $ (selector) to the document element, which is definitely present, so there is no similar situation. The correct replacement method should be:

$ (selector). Live (' click ', function () {/* Some code */}); Replace with $ (document). On (' click ', selector, function () {/* Some code */});
2. The deprecated JQuery.fn.die method is used

JQuery Migrate the warning for this error is:

JQMIGRATE:jQuery.fn.die () is deprecated

This method and the previous live just in turn, cancels the binding of the event handler function. The new version should be replaced with the off function, similar to the replacement method.

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

JQuery Migrate the 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 hiding of elements, the function of this purpose is still present in jquery, and the other is the deprecated toggle function mentioned above, which is used to bind at least two functions to the same element. When you click on the element, two functions alternately execute. These two functions of the same name are far apart and are no longer recommended for use 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. The deprecated Jquery.browser attribute is used

JQuery Migrate the warning for this error is

JQMIGRATE:jQuery.browser is deprecated

In front-end development, we often have to make different processing according to different browser version, Jquery.browser is originally through the browser's useragent field to extract browser-related information. It is deprecated in the new version, but it is recommended to use the method of feature detection and 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 idea, you can implement it yourself. For example, to determine whether IE is not a browser, you can use

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

That is, you manually get the UserAgent field and make a regular expression match. Other browsers have similar ideas, all of which do a regular match for navigator.useragent.

5. $ (HTML) format writing error

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

1. Jqmigrate: $ (HTML) HTML strings must start with ' < ' character2. Jqmigrate: $ (HTML) HTML text after last tag is ignored3. Jqmigrate:html string cannot start with a ' # ' character

This error is quite noteworthy, because the low version of jquery, as we said at the beginning of the article, has an XSS vulnerability, which is actually related to this error. In JavaScript we often write an HTML-formatted string directly into a jquery reference, such as $ (' <div></div> '). In accordance with the new version of jquery, this HTML-formatted string must start with a left angle bracket (less than a sign), and no other characters are allowed. Here are some of the things that are wrong:

1. $ ("<div></div>"); Error, the string starts with a space, not 2 that begins with less than ' < '. $ ("<div></div>test"); No, the HTML tag ends with an extra "test", which is ignored by 3. $ ("#<div></div>"); Error, starting with the pound sign and not behind a CSS selector

This point in the writing time to pay attention to, in fact, it is easy to avoid. The third mistake is not just a warning, but jquery throws an error and stops the JavaScript code from continuing. The general case begins with a pound sign, such as $ ("#test"), which is actually a common selector, but the above example is followed by an HTML string, which is judged by jquery as a potential XSS attack.

6. Incorrect use of the JQuery.fn.attr method (this is a very easy mistake!) )

In JQuery migrate, the warning about the Attr method has the following:

1. JQMIGRATE:jQuery.fn.attr (' value ', Val) no longer sets Properties2. JQMIGRATE:jQuery.fn.attr (' value ') no longer gets properties3. JQMIGRATE:jQuery.fn.attr (' checked ') may use the property instead of Attribute4. JQMIGRATE:jQuery.fn.attr (props, pass) is deprecated

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

$ (' input '). Val (); Gets the input form now entered with the value $ (' input '). Val (' HelloWorld '); Set values for input form inputs

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

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

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

This is the notation used since the jquery 1.6 release. If you set the disabled and selected properties, you also use the Prop method. When do you use the attr method? The difference is that prop sets the intrinsic properties of an element, and attr sets the custom attribute that is written on the HTML tag. As an example:

<input type= "checkbox" checked= "checked" haha= "Hello" >var v1 = $ (' input '). Prop ("checked"); Returns TRUE/FALSE, whether selected, changes var v2 = $ (' input ') as the state changes. attr ("checked"); Return "Checked", which you set on the label, does not change var v3 = $ (' input '). attr ("haha"); Returns "Hello", custom attribute var v4 = $ (' input '). Prop ("haha"); Return undefined, there is no intrinsic property at all

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, the jQuery that triggered the warning is rarely seen, can be ignored.

7. An illegal parameter was passed to the $.parsejson

In 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 own Json.parse interface, which came into effect from jquery 1.9. This problem is common when Ajax receives a service-side return value. The server may return an empty string, at which point the interface is called to produce an error. A valid JSON string must be passed to $.parsejson. Here's how to fix it:

var v1 = $.parsejson (str); Replace with var v1 = $.parsejson (str str: "null");
8. The deprecated ' hover ' event string is used

This error produces the following warning in jquery migrate

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

When registering an event handler, ' hover ' can be used as a nickname for the ' MouseEnter MouseLeave ' two event. The nickname is now 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 jQuery migrate:

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

Two function functions are exactly the same and can be replaced directly.

Above, is a common problem in the jquery upgrade, 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 and are relatively rare, but there is no guarantee that they will not appear in your project, for the reference of interested members only.

  Rare Pits 1. jquery is not compatible with the browser's weird mode

This error trigger method is very simple, directly to the top of the HTML page <! DOCTYPE html> label is deleted. Browser weird mode is designed to be compatible with the old web page, please refer to this article: links. I think the web programmer should not be silly to write doctype, and seldom use the browser in this mode.

The error warning presented by JQuery migrate is as follows:

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

The warning in jQuery migrate is as follows:

Jqmigrate:ajax events should being attached to Document:ajaxstart

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

$ ("#status"). Ajaxstart (function () {$ (this). Text ("Ajax started");}); Modified to $ (document). Ajaxstart (function () {$ ("#status"). Text ("Ajax started");});
3. IE6/7/8 Browser does not support modifying the Type property of the input form

This is the warning in jquery migrate:

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

Change the Type property of the form input, you can directly change the text box to a single box, change to a multi-box and so on. Although I feel that this is not an elegant behavior, but many browsers are supported to do so, in addition to IE6/7/8. It is also advisable to use this function sparingly in practice.

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

This is the warning in jquery migrate:

1. JQMIGRATE:jQuery.clean () is deprecated2. JQMIGRATE:jQuery.event.handle is undocumented and deprecated3. JQMIGRATE:jQuery.attrFn is deprecated4. Jqmigrate:use of JQuery.fn.data (' events ') is Deprecated5. Jqmigrate:global events is undocumented and deprecated

If you have used these five interfaces in your own code, it is really the expert who has studied the jquery source code carefully. Since these five interfaces have never appeared in the official jquery documentation, and some have been deleted in subsequent versions, there is no shadow to go without a trace. Look at the source code words in earlier versions have the opportunity to find their presence, but it is not recommended to use. It is recommended to use other methods to implement the corresponding functions. What the? You don't know what these five functions are? That's better, you don't need to know now ...

5. Outdated $.sub () method used

The warning for this issue in 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 used at the beginning of the jquery 1.7 release.

6. Outdated JQuery.fn.error methods are used

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

JQMIGRATE:jQuery.fn.error () is deprecated

In jquery, the error is also the same as the Click event. The handler function that registered the event, formerly $ (selector). Error (function () {}), is now obsolete and can be substituted with $ (selector). On (' Error ', function () {}).

  Sample Code

Since this article called itself "xx Daquan", it should be as comprehensive as possible. In order to understand how these pits are stepping in, we end up writing a JS code that requires a minimum of code to migration all the pits in the jquery library ... That is, let the jquery migration library print out all the warnings it can print. The final code looks like this (the blog park has no way to upload attachments, only paste code), very easy to understand. Open the Index.html file, and then press F12 to open the console, and you can see the magnificent console warning ^_^

<!--filename:index.html--><!--<! DOCTYPE html>-->//keng0 Weird mode 

jquery Upgrade Pit Daquan

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.