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: <pre class="brush:php;toolbar:false">while ( (fn = ready[ i++ ]) ) { fn.call( document, jQuery ); }</pre>
becomes: <pre class="brush:php;toolbar:false">readyList.fire( document , [ jQuery ] );</pre>
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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
