An introduction to some improved details of jQuery
jquery API”>jQuery 1.5 beta1 is out. In terms of learning and follow-up, this time it is relatively late (I don’t even know when 1.5 came out as alpha, so it is just beta).
The biggest update of version 1.5 is the complete rewriting of AJAX, which provides stronger scalability. However, due to energy and space constraints, the analysis of the new AJAX will be left to another time. This article will briefly introduce the details. Improvements.
jQuery._Deferred and jQuery.Deferred
First of all, I have to talk about these two new things, because they exist as infrastructure, and I don’t understand these two things clearly. Some problems cannot be explained at all.
jQuery.Deferred is an enhanced version of jQuery._Deferred
, so for this problem, start with jQuery._Deferred.
It will explain most of the problem What is Deferred? Literally, my first reaction is "lazy loading", the first letter should be the definition of "type". , so this is probably a type of "transparently providing lazy loading function". However, in fact, although it does have a little bit of "delay" meaning, this thing is not used to implement lazy loading
jQuery._Deferred
is a function queue. Its functions are as follows:##Save several functions.
- Execute all the saved functions at a specific time.
- ##After execution, the new incoming functions will be executed immediately. #Does it feel similar to something? Yes, jQuery's ready function has this kind of logic. In fact, the ready function in jQuery 1.5 has indeed been grafted onto it.
- jQuery._Deferred provides the following interface:
:
function(fn1, fn2, …), in the form To add a function to the queue
- ##fire
- :
function(context, args)
args, use
context##. #Specifythis
object, specify parameters, and call all functions in the queue. After - fire
is called, _Deferred will enter the
isResolvedisResolved
state. Future calls todone
will no longer save the function, but call the function directly.resolve
: Equivalent to callingfire(this, arguments)
, a simplified method. : Used to determine whether _Deferred is in the - isResolved
state. For details, please refer to the explanation of the previous
fire
function. . - cancel
: Cancel the entire queue, so that no matter whether
jQuery._Deferredfire
occurs in the future, the functions in the queue will not be called again.Now that
is explained, let’s take a look at - jQuery.Deferred
. This thing is actually composed of two _Deferreds. The first one is called
jQuery.Deferreddeferred
, which is used to store functions in the "normal" state; the second one is calledfailDeferred
, which is used to store functions in the "normal" state. Save functions in "error" state. At the same time, provides some new interfaces:
then
: function(done, fail) In the form, add done to deferred
and
- to
- failedDeferred
.
fail
: Equivalent to thedone
function offailDeferred
. - fireReject
: Equivalent to the
fire
function offailDeferred
. - reject
: Equivalent to the
resolve
function offailDeferred
. - isRejected
: Equivalent to the
isResolved
function offailDeferred
. At the same time, - jQuery.Deferred
cancels the
cancel
function.So what is this used for? There are two states of "normal" and "error", and it is asynchronous at the same time. It is easy to think of... Yes, it is used for AJAX. I will explain it in detail in the next analysis.
Changes in jQuery.ready
Because of the
, the jQuery.ready
function becomes dependent on the function queue, specifically The changes include: The original
variable is no longer an array, but has become a
jQuery._Deferredobject.
Originally in DOMContentLoaded
, the logic of calling all functions in readList
is now also used in
, the original code: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">while ( (fn = ready[ i++ ]) ) { fn.call( document, jQuery ); }</pre><div class="contentsignin">Copy after login</div></div>
becomes: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">readyList.fire( document , [ jQuery ] );</pre><div class="contentsignin">Copy after login</div></div>
jQuery.parseXML function
Added static function jQuery.parseXML to provide browser-compatible Function to convert string
to XML document. There are many logics for this function on the Internet, and there is nothing special about jQuery. They are roughly divided into the following two types:
For standard browsers, use the
DOMParserobject:
var parser = new DOMParser(); var xml = parser.parseFromString(text, 'text/html');
For IE, use the 添加了 修改了 这样保证在同一时间,引入多个jQuery副本,这几个副本之间的expando不会相互冲突,导致元素上的data变得错乱。一般来说,是不会引入多个jQuery副本的,但是使用SealJS等的时候,配置不当的话,也是很容易出现此类问题的。 原本的 在1.4.4版本中,jQuery会在页面unload的时候清理掉由jQuery维护的所有DOM事件,这是为了避免IE的内存泄露问题。但是在1.5中这一段代码不见了,不知是出于什么考虑。 对于IE下使用 IE中有个叫 IE中还有一个叫 另外 AJAX已经完全重写了,只留下一点边边角角保留着1.4.4版本的风采,这里只抽取一部分进行简单的说明。 原来版本中 AJAX的回调函数中,作为参数的对象不再是原生的 原本对于“请求成功”的浏览器状态码,除200-299以及304外,还有一个1223,来自于IE的一个BUG,会将204的状态码变成1223。现在因为有了jXHR对象,相当于中间多了一层,因此从jXHR对象获取 再添加了这个回调后, 根据返回的状态码,触发 根据状态码,触发对应的statusCode回调。 触发 触发全局 如果此时没有正在执行的AJAX,触发全局 入口函数 jQuery对象支持继承了,具体的修改是将几处直接调用jQuery的代码改为了对 同时还提供了Microsoft.XMLDOM
object: var parser = new ActiveXObject('Microsoft.XMLDOM'); parser.async = 'false'; parser.loadXML(text); var xml = parser.documentElement;
data部分
jQuery.hasData
函数,用于判断一个元素是否有jQuery附加上去的数据。jQuery.expando
的实现,在原来单纯地取当前时间的基础上,添加了一个随机数:expando = "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( //D/g, "" );
DOM操作部分
hasClass
、addClass
、removeClass
函数都需要将元素的class属性分隔为数组,在1.4.4版本中,通过/n或/t进行分隔,在1.5中增加了一个/r,用于对应Windows平台下的换行符(/r/n)。jQuery.fn.attr
函数,1.4.4版本中拒绝从TextNode和CommentNode上获取属性,在1.5版本中添加了一个AttributeNode(noteType == 2)。cloneNode
复制节点,会将事件也一起复制过来的问题,1.4.4中是采取复制innerHTML
的方式给予解决,而在1.5中则采纳了mootools团队提供的方法,使用cloneFixAttribute
函数修正该问题。cloneFixAttribute
函数们于jQuery 1.5 beta1源码文件的5388-5438行,处理IE的BUG的原理很简单,当然前端里一些看似简单的东西,都是很难发现的:
clearAttributes
的函数,会清除到节点上的所有属性,顺便把和事件相关的<a href="http://www.php.cn/wiki/1449.html" target="_blank">onclick</a>
之类的属性也去掉了。在复制出来的节点上调用这个函数,就会把属性清得干干净净。mergeAttributes
的函数,把一个节点的属性复制到另一个节点上,但他不会把和事件相关的属性复制过去。所以再把原始节点调用mergeAttributes
,把属性重新放回复制出来的节点上,这就相当于起到了去除事件相关属性的作用。cloneFixAttribute
函数还处理了非常多IE6-8在cloneNode
上的兼容性问题,非常值得详细研究。AJAX部分
$.get
和$.post
的实现非常相似,具体来说仅有一个method配置项不同,因此在1.5版本中被合并起来了:$.each(['get', 'post'], function(i, method) { $[method] = function() { ... }; });
ajaxSetup
函数现在加了一行return this;
,可以链式调用了。serializeArray
函数现在统一将value中的换行符替换成Windows的风格(/r/n
)。XMLHTTPRequest
,而是jQuery自己封装的称为jXHR的对象,这个对象提供了XMLHTTPRequest
的常用接口。statusCode
不会出现1223的情况,已经被变回204了。jQuery.ajax
函数的配置项中多了一个statusCode
项,其结构为map,用于指定返回特定状态码时的回调函数,大致形式如下:jQuery.ajax({ url: 'xxx', statusCode: { 200: function() { 处理请求成功 }, 404: function() { 处理页面未找到 }, 503: function() { 处理Service Unavailable } } });
jQuery.ajax
函数已经有非常多的回调函数,其触发过程如下:
success
或者error
回调。complete
回调。ajaxComplete
回调。ajaxStop
回调。其他细节
jQuery.fn.init
现在多了一个参数,值始终为rootjQuery
,用于加速init
函数中对rootjQuery
变量的查找速度(减少了一层作用域):// jQuery 1.5 beta1 源码23行 jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }
this.constructor
的调用:// 202行: return this.constructor( context ).find( selector ); // 253行: var ret = this.constructor(); // 334行: return this.prevObject || this.constructor(null);
jQuery.subclass
函数用于创建一个继承自jQuery的类型,由于不是很常用jQuery,更是从来没有用到过需要继承jQuery的情况,因此也不方便说这个功能的作用有多大。
The above is the detailed content of An introduction to some improved details of jQuery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Improvements in PHP7: No more undefined errors. PHP7 is a major version update of the PHP language, which brings many important improvements and optimizations. One of the significant improvements is that undefined errors no longer appear when dealing with undefined variables, which brings a better user experience to developers. Before PHP7, if undefined variables were used in the code, an undefined error would occur. Developers needed to manually check or set the error reporting level to avoid this situation.

The eighth color is a weapon in Neon Abyss. Many players want to know about the ballistics of the eighth color of the weapon and how to play with the weapon strength. So let’s take a look at the detailed guide to Neon Abyss’ eighth color weapon trajectory, weapon strength, and weapon gameplay. Neon Abyss Color 8 Detailed Guide Weapon Introduction: The Wizard’s Secret Weapon! Weapon attack speed: Normal Weapon strength: Moderate Weapon gameplay: The attack method of the eighth color is three single-target attacks and then launches a ray. Ballistic display:

A fast score query tool provides students and parents with more convenience. With the development of the Internet, more and more educational institutions and schools have begun to provide online score check services. To allow you to easily keep track of your child's academic progress, this article will introduce several commonly used online score checking platforms. 1. Convenience - Parents can check their children's test scores anytime and anywhere through the online score checking platform. Parents can conveniently check their children's test scores at any time by logging in to the corresponding online score checking platform on a computer or mobile phone. As long as there is an Internet connection, whether at work or when going out, parents can keep abreast of their children's learning status and provide targeted guidance and help to their children. 2. Multiple functions - in addition to score query, it also provides information such as course schedules and exam arrangements. Many online searches are available.

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold
