Skip to content

Jquery 版本3迁移

ythy edited this page Oct 26, 2017 · 4 revisions

jQuery 3.0 Final Released on June 9, 2016
This version has been in the works since October 2014. We set out to create a slimmer, faster version of jQuery (with backwards compatibility in mind). We’ve removed all of the old IE workarounds and taken advantage of some of the more modern web APIs where it made sense. It is a continuation of the 2.x branch, but with a few breaking changes that we felt were long overdue. While the 1.12 and 2.2 branches will continue to receive critical support patches for a time, they will not get any new features or major revisions. jQuery 3.0 is the future of jQuery. If you need IE6-8 support, you can continue to use the latest 1.12 release.

To assist with upgrading, we have a brand new 3.0 Upgrade Guide. And the jQuery Migrate 3.0 plugin will help you to identify compatibility issues in your code.

Slim build

Finally, we’ve added something new to this release. Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’re releasing a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version – 23.6k vs 30k. https://code.jquery.com/jquery-3.0.0.slim.js

Browser Support

  • Internet Explorer: 9+
  • Chrome, Edge, Firefox, Safari: Current and Current - 1
  • Opera: Current
  • Safari Mobile iOS: 7+
  • Android 4.0+

Summary of Important Changes

Ajax

  • Feature: New signature for jQuery.get() AND jQuery.post()

Attributes

  • Breaking change: .removeAttr() no longer sets properties to false

    Prior to jQuery 3.0, using .removeAttr() on a boolean attribute such as checked, selected, or readonly would also set the corresponding named property to false. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.

    It is almost always a mistake to use .removeAttr( "checked" ) on a DOM element. The only time it might be useful is if the DOM is later going to be serialized back to an HTML string. In all other cases, .prop( "checked", false ) should be used instead.

  • Breaking change: select-multiple with nothing selected returns an empty array

    Before jQuery 3.0, calling .val() on a <select multiple> element with no elements selected returned null. This was inconvenient since if at least one value was selected the return value would be an array. Also, if all options are disabled jQuery already returned an empty array. To improve consistency, the nothing-selected case now returns an empty array.

Core

  • Breaking change: jQuery 3.0 runs in Strict Mode
  • Breaking change: document-ready handlers are now asynchronous
$(function(){
   console.log("ready");
});
console.log("outside ready");
// outside ready
// ready
  • Breaking change: jQuery.isNumeric() and custom .toString()
    The jQuery.isNumeric() method is intended to be used with primitive numbers and strings that can be coerced to finite numbers. In particular, it no longer tries to obtain numbers from objects that have a .toString() method.

  • Breaking change: Return values on empty sets are undefined
    With few exceptions, any value-returning jQuery methods should return undefined on an empty jQuery collection in keeping with our API guidelines.

    • Dimensional methods: .width(), .height(), .innerWidth(), .innerHeight(), .outerWidth(), and .outerHeight()
    • Offset methods: .offsetTop() and .offsetLeft()

    Previously, these methods returned null instead of undefined for an empty collection.

  • Feature: for...of loops can be used on jQuery collections

for ( let elem of $elems ) {
  // work with elem
}
  • Feature: jQuery.ready promise is formally supported
$.when( $.ready, $.getScript("optional.js") ).then(function() {
   // the document is ready and optional.js has loaded/run
}).catch( function() {
   // an error occurred
});

  • Deprecated: jQuery.parseJSON()
    Since all the browsers supported by jQuery 3.0 support the native JSON.parse() method, we are deprecating jQuery.parseJSON().

  • Deprecated: document-ready handlers other than jQuery(function)
    Due to historical compatibility issues there are a multitude of ways to set a document ready handler. All of the following are equivalent and call the function fn when the document is ready:

    • $(fn);
    • $().ready(fn);
    • $(document).ready(fn);
    • $("selector").ready(fn);

    As of jQuery 3.0 the recommended way to add a ready handler is the first method, $(fn). As noted in the Event section, the $(document).on("ready", fn) event form has slightly different semantics and was removed in jQuery 3.0.

Data

  • Breaking change: .data() names containing dashes
    As of jQuery 3.0, all data names are stored in jQuery's internal data object in camelCase (e.g., clickCount), rather than kebab-case (e.g. click-count). This is consistent with the way that standard DOM turns dashed names into camel case for JavaScript names in CSS and data properties.

    In general, kebab case still works in jQuery 3.0 when setting or getting a specific data item, e.g. .data("right-aligned"), but if you retrieve the internal data object it will now have the data item in camel case (rightAligned). The main difference in 3.0 is when you use kebab case names directly on the data object instead of using the .data() API to get or set them.

var $div = $("<div />");
$div.data("clickCount", 2);
$div.data("clickCount"); // 2
$div.data("click-count", 3);
$div.data("clickCount"); // 3
$div.data("click-count"); // 3

var allData = $div.data();
allData.clickCount; // 3
allData["click-count"]; // undefined
allData["click-count"] = 14;
$div.data("click-count"); // 3, NOT 14 as it would be in jQuery 2.x
allData.clickCount; // 3
allData["click-count"]; // 14

Dimensions

  • Breaking change: .width(), .height(), .css("width"), and .css("height") can return non-integer values
    Before version 3.0, jQuery used the DOM offsetWidth and offsetHeight properties to determine the dimensions of an element, and these properties always return integers. With jQuery 3.0 we get more precise values via the DOM getBoundingClientRect API, and these may may not be integers. If your code always expects integers for dimensions, it may need to be adjusted to deal with this extra precision.
  • Breaking change: .outerWidth() or .outerHeight() on window includes scrollbar width/height
    $(window).outerWidth() method now returns the width including scrollbar width. This is equivalent to the DOM property window.innerWidth. The same applies for .outerHeight().

Effects

  • Breaking change: .show(), .hide(), and .toggle() methods now respect more stylesheet changes

    ?? 待检讨 If you have elements in a stylesheet that are set to display: none , the .show() method will no longer override that.

    ?? 待检讨 If you need an element to be hidden by default, the best way is to add a class name like “hidden” to the element and define that class to be display: none in a stylesheet. Then you can add or remove that class using jQuery’s .addClass() and .removeClass() methods to control visibility. Alternately, you can have a .ready() handler call .hide() on the elements before they are displayed on the page. Or, if you really must retain the stylesheet default, you can use .css(“display”, “block”) (or the appropriate display value) to override the stylesheet.
    结论:CSS: try more simplified approach to show/hide methods 以上2段改善内容被恢复 As we discussed, we're going to be taking a different direction here and revert to the old behavior with a minor difference: only cache the display value if one exists inline that we did not put there ourselves.

in 3.0 we have -

/*case #1*/$("<div/>").show().appendTo("body")[0].style.display; // ""
/*case #2*/$("<div/>").hide().appendTo("body")[0].style.display; // "none"

Whereas before, in 2.x, we had -

/*case #2*/$("<div/>").show().appendTo("body")[0].style.display; // "block"
/*case #2*/$("<div/>").hide().appendTo("body")[0].style.display; // "none"

  • Feature: Animations now use requestAnimationFrame
    On platforms that support the requestAnimationFrame API, which is pretty much everywhere but IE9, jQuery will now use that API when performing animations. This should result in animations that are smoother and use less CPU time—and save battery as well on mobile devices.

Event

  • Breaking change: .load(), .unload(), and .error() removed
    These methods are shortcuts for event operations, but had several API limitations. The event .load() method conflicted with the ajax .load() method. The .error() method could not be used with window.onerror because of the way the DOM method is defined. If you need to attach events by these names, use the .on() method, e.g. change $("img").load(fn) to $("img").on("load", fn).

  • Breaking change: .on("ready", fn) removed

  • Deprecated: .bind() and .delegate()
    Five years ago in jQuery 1.7 we introduced the .on() method for attaching event handlers. The older .bind(), .unbind(), .delegate() and .undelegate() methods are being deprecated as of 3.0, but are still present. The API documentation explains how to rewrite the calls using the .on() and .off() methods.

Offset

  • Breaking change: Invalid input to the .offset() method
    When using the .offset() method, the first item in the jQuery collection must be a DOM element that has a DOM getBoundingClientRect() method. (All browsers supported by jQuery 3.0 have this API.) Any other input may result in jQuery throwing an error.

Selector

  • Breaking change: Behavior of :hidden and :visible
    An element is considered now visible if it has a layout box returned from the DOM getClientRects() method, even if that box has a height and/or width of zero. This means that elements such as <br /> or an empty <span> element that don't have height are considered to be visible.
Clone this wiki locally