search
HomeWeb Front-endJS TutorialjQuery 1.9.1 Source Code Analysis Series (14) Commonly Used jQuery Tools_jquery

In order to prepare for the next chapter of analyzing animation processing, let’s take a look at some tools first. The queue tool is often used in animation processing.

jQuery.fn. queue(([ queueName ] [, newQueue ]) || ([ queueName ,] callback )) (Gets or sets the function queue to be executed on the current matching element. If the current jQuery object matches multiple elements : When getting the queue, only get the queue on the first matching element; when setting the queue (replacement queue, append function), set it separately for each matching element if you need to remove and execute the first one in the queue. function, please use the dequeue() function. You can also use the clearQueue() function to clear the specified queue)

jQuery.fn. dequeue([ dequeueName ]) (removes the first function in the specified queue of each matching element and executes the removed function. You can also use the clearQueue() function to clear the specified queue (The functions in it will not be executed))

jQuery.fn. clearQueue([ dequeueName ]) (clear all unexecuted items in the specified queue of each matching element)

jQuery.error(msg) (Throws an exception containing the specified string information.)

jQuery.each(object, callback) (traverses the specified object and array, and uses each property of the object (or each member of the array) as the context to traverse and execute the specified function. The so-called context means the The this pointer inside the function refers to the element. This function belongs to the global jQuery object. Note that this is different from the each() function of the jQuery object (instance), but the each() implementation of the jQuery object (instance) also calls jQuery.each. )

jQuery.proxy() (Change the context of the function. You can pass the specified function into this function, which will return a new function. Its execution code remains unchanged, but the context (this) inside the function has been changed. For the specified value

 Usage 1:

jQuery.proxy( function, context [, additionalArguments ] )

Change the context object of the function function to the specified context.

Usage 2:

jQuery.proxy( context, name [, additionalArguments ] )

Change the context of the function named name to the specified context. Function name should be an attribute of the context object.

jQuery.map(object, callback) (Use the specified function to process each element in the array (or each attribute of the object), and encapsulate the processing results as a new array and return it. There is also a jQuery library with the same name Instance method jQuery.fn.map(), which is only used to traverse the elements matched by the current jQuery object)

jQuery.fn.data([ key [, value ] ]) (access data on all elements matched by the current jQuery object)

jQuery.fn.removeData(keys) (removes the data item with the specified key stored on each element matched by the current jQuery object)

jQuery.support (returns feature or bug information of the browser currently used by the user. This property is an object. The properties of this object are not immutable, and jQuery does not guarantee that the specified properties will be available in future versions. , these properties are mainly used by plugin or kernel developers)

jQuery.contains(container, contained) (determine whether the specified element contains another element. In short, this function is used to determine whether another DOM element is a descendant of the specified DOM element)

jQuery.extend([ deep ], target , object1 [, objectN... ]) (Merge the contents of one or more objects into the target object. This function can add member properties and methods of one or more objects Copy to the specified object, the parameter deep is used to indicate whether to merge deeply recursively)

jQuery.fn.extend(object) (extends one or more instance properties and methods for jQuery (mainly used for extension methods))

jQuery.globalEval(code) (globally executes a piece of JavaScript code. This function is similar to the regular JavaScript eval() function. The difference is that the scope of the code executed by jQuery.globalEval() is the global scope)

jQuery.grep(array, function [, invert ]) (uses the specified function to filter the elements in the array and returns the filtered array. The source array will not be affected, and the filtering results are only reflected in the returned result array )

jQuery.inArray(value, array [, fromIndex ]) (Search for the specified value in the array and return its index value. If the value does not exist in the array, it returns -1)

jQuery.isArray(object) (determines whether the specified parameter is an array)

jQuery.isEmptyObject(object) (determines whether the specified parameter is an empty object. The so-called "empty object" does not include any enumerable (custom) attributes. In short, the object has no attributes. Iterate through for...in)

jQuery.isPlainObject(object) (determines whether the specified parameter is a pure object. The so-called "pure object" means that the object is created through "{}" or "new Object")

jQuery.isFunction(object) (determines whether the specified parameter is a function)

jQuery.isNumeric(value) (determines whether the specified parameter is a numeric value)

jQuery.isWindow(object) (determines whether the specified parameter is a window)

jQuery.isXMLDoc(node) (determines whether a DOM node is located in an XML document, or is itself an XML document. This function is mainly used to determine whether the specified document is an XML document or an HTML (or XHTML) document)

jQuery.makeArray(object) (converts an array-like object into a real array object. The so-called "array-like object" is a regular Object object, but it is very similar to an array object: it has a length attribute and ends with 0 , 1, 2, 3... and other numbers as attribute names. However, it is not an array after all, and there are no built-in methods inherited from the prototype object of the array (for example: push(), sort(), etc.)

jQuery.noop() (is an empty function, it does nothing. When sometimes you need to pass in function parameters and want it to do nothing, you can use this function, and there is no need to Create a new empty function)

jQuery.now() (returns the number of milliseconds since midnight on January 1, 1970. This function is similar to new Date().getTime())

jQuery.parseHTML(htmlString [, context ] [, keepScripts ]) (parse the HTML string into the corresponding DOM node array. This function will use the native DOM element creation function to convert the HTML string into a DOM element Collection, you can insert these DOM elements into the document)

jQuery.parseJSON(jsonString) (Convert a well-formed JSON string into its corresponding JavaScript object. The so-called "well-formed" means that the specified string must conform to the strict JSON format, for example: the attribute name must Add double quotes, and string values ​​must also use double quotes. If a JSON string with an incomplete format is passed in, a JS exception will be thrown)

jQuery.parseXML(XMLString) (parse the string into the corresponding XML document. This function will use the browser's built-in parsing function to create a valid XML document, which can be passed into the jQuery() function to create a A typical jQuery object, allowing it to be traversed or otherwise manipulated)

jQuery.trim(str) (Remove whitespace characters at both ends of the string. This function can remove whitespace characters at both ends of the string (until the first non-whitespace string is encountered). It will clear including newlines symbols, spaces, tabs and other common whitespace characters)

jQuery.type(object)(确定JavaScript内置对象的类型,并返回小写形式的类型名称。JavaScript也自带有一个typeof运算符,可以确定数据的类型。不过,对于绝大多数对象而言,typeof运算符都返回"object",无法区分具体的类型。jQuery.type()可以更加精确地确定JS内置对象的类型。例如:对于new Number(5),typeof返回"object",jQuery.type()返回"number";对于new Date(),typeof返回"object",jQuery.type()返回"date"。type的返回的结果有"Boolean Number String Function Array Date RegExp Object Error"的小写)

jQuery.unique(array)(根据元素在文档中出现的先后顺序对DOM元素数组进行排序,并移除重复的元素。

  注意:该函数仅作用于DOM元素数组,而不是数字、字符串或其他类型。此外,这里的重复指的是两个元素实际上是同一个元素(通过全等"==="来判断),而不是指两个属性相同的元素。

  警告:通过实际测试发现,该函数并不能按照预期返回正确的结果。在不同的浏览器中、在不同版本的jQuery中,其返回结果可能不一致(请参考下面的演示代码))

jQuery.fn.promise([type,] obj)(获取已解决的延时对象的promise,并和obj对象合并。并给指定类型的队列清空的时候(默认的类型是FX)添加解决处理)

a.jQuery.trim源码详解

  trim函数有两个分支,第一个分支是:如果浏览器支持trim函数,则使用浏览器本地的trim函数;否则走第二个分支使用正则去除前后两边的空白。

//如果可以则使用浏览器支持的trim函数
// core_version.trim
jQuery.trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
  return text == null ?
  "" :
  core_trim.call( text );
} :
//否则使用正则去除前后两端的空白符
//rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
function( text ) {
  return text == null ?
  "" :
  ( text + "" ).replace( rtrim, "" );
},

b. 队列(queue)详解

jQuery.fn.queue( type, data )
  处理步骤如下:
  默认队列是fx类型的标准动画效果队列。如果队列类型不是字符串,则需要按默认类型调整数据。
if ( typeof type !== "string" ) {
  data = type;
  type = "fx";
  setter--;
}

  根据参数判断是获取还是设置指定类型的队列。

  如果是获取直接获取当前jQuery匹配的元素的第一个元素对应类型的队列;

//获取指定类型的队列
if ( arguments.length < setter ) {
  return jQuery.queue( this[0], type );
}

  如果是设置,则遍历当前jQuery匹配的元素,给每个元素都设置指定类型的队列,并给每一个元素设置相应的hooks(用来做拓展处理,比如最后清除队列使用)

return data === undefined &#63;
this :
//每一个jQuery的元素都添加队列
this.each(function() {
  var queue = jQuery.queue( this, type, data );
  //确保队列有一个hooks。执行完这段代码以后保存了一个清空队列的函数empty
  jQuery._queueHooks( this, type );
  //如果为"fx"(表示jQuery中的标准动画效果队列),并且队列中第一个函数没有正在执行
  //则执行队列中第一个函数。可见动画队列添加后会立马执行动画
  if ( type === "fx" && queue[0] !== "inprogress" ) {
    jQuery.dequeue( this, type );
  }
})

  函数中使用了低级api jQuery.queue函数,是获取/设置队列的基础接口,源码如下

queue: function( elem, type, data ) {
  var queue;
  if ( elem ) {
    //先获取相应类型的队列
    type = ( type || "fx" ) + "queue";
    queue = jQuery._data( elem, type );
    //在队列末尾添加函数
    if ( data ) {
      if ( !queue || jQuery.isArray(data) ) {
        queue = jQuery._data( elem, type, jQuery.makeArray(data) );
      } else {
        queue.push( data );
      }
    }
    return queue || [];
  }
}

c.jQuery.fn.dequeue

  移除每个匹配元素的指定队列中的第一个函数,并执行被移除的函数。内部调用jQuery.dequeue来实现。jQuery.dequeue的源码如下

  jQuery.dequeue中需要特别注意的是对FX动画队列的处理

dequeue: function( elem, type ) {
  type = type || "fx";
  var queue = jQuery.queue( elem, type ),
    startLength = queue.length,
    fn = queue.shift(),//取出队列中第一个函数
    hooks = jQuery._queueHooks( elem, type ),
    next = function() {
      jQuery.dequeue( elem, type );
    };
  //如果FX队列中出列,总是取出进度点
  if ( fn === "inprogress" ) {
    fn = queue.shift();
    startLength--;
  }
  hooks.cur = fn;
  if ( fn ) {
    // 添加进度定点,以防止FX队列自动dequeue
    if ( type === "fx" ) {
      queue.unshift( "inprogress" );
    }
    // 清理最后一个队列停止函数
    delete hooks.stop;
    //next和hooks会传递给回调
    fn.call( elem, next, hooks );
  }
  //队列长度为0且hooks存在,则删除队列
  if ( !startLength && hooks ) {
    hooks.empty.fire();
  }
}

  注意执行队列中函数传递的参数( elem, next, hooks )。

以上所述就是小编给大家分享的jQuery 1.9.1源码分析系列(十四)之常用jQuery工具,希望大家喜欢。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.