Detailed explanation of the use of init constructor in jQuery
这次给大家带来jQuery内init构造器使用详解,jQuery内init构造器使用的注意事项有哪些,下面就是实战案例,一起来看一下。
init 构造器
由于这个函数直接和 jQuery()
的参数有关,先来说下能接受什么样的参数。
源码中接受 3 个参数:
init: function (selector, context, root) { ... }
jQuery()
,空参数,这个会直接返回一个空的 jQuery 对象,return this。jQuery( selector [, context ] )
,这是一个标准且常用法,selector 表示一个 css 选择器,这个选择器通常是一个字符串,#id 或者 .class 等,context 表示选择范围,即限定作用,可为 DOM,jQuery 对象。jQuery( element|elements )
,用于将一个 DOM 对象或 DOM 数组封装成 jQuery 对象。jQuery( jQuery object|object )
,会把普通的对象或 jQuery 对象包装在 jQuery 对象中。jQuery( html [, owner<a href="http://www.php.cn/code/658.html" target="_blank">Document</a> ] )
,这个方法用于将 html 字符串先转成 DOM 对象后在生成 jQuery 对象。jQuery( html, attributes )
,和上一个方法一样,不过会将 attributes 中的方法和属性绑定到生成的 html DOM 中,比如 class 等。jQuery( callback )
,此方法接受一个回掉函数,相当于 window.onload 方法,只是相对于。
介绍完入口,就开始来看源码。
init: function (selector, context, root) { var match, elem; // 处理: $(""), $(null), $(undefined), $(false) if (!selector) { return this; } // rootjQuery = jQuery( document ); root = root || rootjQuery; // 处理 HTML 字符串情况,包括 $("<p>")、$("#id")、$(".class") if (typeof selector === "string") { //此部分拆分,留在后面讲 // HANDLE: $(DOMElement) } else if (selector.nodeType) { this[0] = selector; this.length = 1; return this; // HANDLE: $(function) } else if (jQuery.isFunction(selector)) { return root.ready !== undefined ? root.ready(selector) : // Execute immediately if ready is not present selector(jQuery); } return jQuery.makeArray(selector, this); }
上面有几点需要注意,root = root || rootjQuery;
,这个参数在前面介绍用法的时候,就没有提及,这个表示 document,默认的话是 rootjQuery,而 rootjQuery = jQuery( document )
。
可以看出,对于处理 $(DOMElement)
,直接是把 jQuery 当作一个数组,this[0] = DOMElement
。其实,这要从 jQuery 的基本构造讲起,我们完成一个 $('p.span')
之后,然后一个 jQuery 对象(this),其中会得到一组(一个)DOM 对象,jQuery 会把这组 DOM 对象当作数组元素添加过来,并给一个 length。后面就像一些链式函数操作的时候,若只能对一个 DOM 操作,比如 width、height,就只对第一个元素操作,若可以对多个 DOM 操作,则会对所有 DOM 进行操作,比如 css()。
jQuery 大题思路如下,这是一个非常简单点实现:
jQuery.prototype = { // 简单点,假设此时 selector 用 querySelectorAll init: function(selector){ var ele = document.querySelectorAll(selector); // 把 this 当作数组,每一项都是 DOM 对象 for(var i = 0; i < ele.length; i++){ this[i] = ele[i]; } this.length = ele.length; return this; }, //css 若只有一个对象,则取其第一个 DOM 对象 //若 css 有两个参数,则对每一个 DOM 对象都设置 css css : function(attr,val){ for(var i = 0; i < this.length; i++){ if(val == undefined){ if(typeof attr === 'object'){ for(var key in attr){ this.css(key, attr[key]); } }else if(typeof attr === 'string'){ return getComputedStyle(this[i])[attr]; } }else{ this[i].style[attr] = val; } } }, }
所以对于 DOMElement 的处理,直接将 DOM 赋值给数组后,return this。
jQuery.makeArray
是一个绑定 数组的函数,和上面的原理一样,后面会谈到。
在介绍下面的内容之前,先来介绍一个 jQuery 中一个识别 Html 字符串的正则表达式,
var rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/; rquickExpr.exec('<p>') //["<p>", "<p>", undefined] rquickExpr.exec('<p></p>') //["<p></p>", "<p></p>", undefined] rquickExpr.exec('#id') //["#id", undefined, "id"] rquickExpr.exec('.class') //null
上面这一系列的正则表达式 exec,只是为了说明 rquickExpr 这个正则表达式执行后的结果,首先,如果匹配到,结果数组的长度是 3,如果匹配到
这种 html,数组的第三个元素是 underfined,如果匹配到 #id,数组的第二个元素是 underfined,如果匹配不到,则为 null。
另外还有一个正则表达式:
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); rsingleTag.test('<p></p>') //true rsingleTag.test('<p ></p>') //true rsingleTag.test('<p class="cl"></p>') //false rsingleTag.test('<p></dp>') //false
这个正则表达式主要是对 html 的字符串进行验证,达到不出差错的效果。在这里不多介绍 exec 和正则表达式了。
下面来看下重点的处理 HTMl 字符串的情况:
if (selector[0] === "<" && selector[selector.length - 1] === ">" && selector.length >= 3) { // 这个其实是强行构造了匹配 html 的情况的数组 match = [null, selector, null]; } else { match = rquickExpr.exec(selector); } // macth[1] 限定了 html,!context 对 #id 处理 if (match && (match[1] || !context)) { // HANDLE: $(html) -> $(array) if (match[1]) { //排除 context 是 jQuery 对象情况 context = context instanceof jQuery ? context[0] : context; // jQuery.merge 是专门针对 jQuery 合并数组的方法 // jQuery.parseHTML 是针对 html 字符串转换成 DOM 对象 jQuery.merge(this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true)); // HANDLE: $(html, props) if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) { for (match in context) { // 此时的 match 非彼时的 match if (jQuery.isFunction(this[match])) { this[match](context[match]); // ...and otherwise set as attributes } else { this.attr(match, context[match]); } } } return this; // 处理 match(1) 为 underfined 但 !context 的情况 } else { elem = document.getElementById(match[2]); if (elem) { // this[0] 返回一个标准的 jQuery 对象 this[0] = elem; this.length = 1; } return this; } // 处理一般的情况,find 实际上上 Sizzle,jQuery 已经将其包括进来,下章详细介绍 // jQuery.find() 为 jQuery 的选择器,性能良好 } else if (!context || context.jquery) { return (context || root).find(selector); // 处理 !context 情况 } else { // 这里 constructor 其实是 指向 jQuery 的 return this.constructor(context).find(selector); }
关于 nodeType,这是 DOM 的一个属性,详情 Node.nodeType MDN。nodeType 的值一般是一个数字,比如 1 表示 DOM,3 表示文字等,也可以用这个值是否存在来判断 DOM 元素,比如 context.nodeType。
整个 init 函数等构造逻辑,非常清晰,比如 (selector, context, root) 三个参数,分别表示选择的内容,可能存在的的限制对象或 Object,而 root 则默认的 jQuery(document)
。依旧采用 jQuery 常用的方式,对每一个变量的处理都非常的谨慎。
如果仔细看上面两部分源代码,我自己也加了注释,应该可以把整个过程给弄懂。
find 函数实际上是 Sizzle,已经单独出来一个项目,被在 jQuery 中直接使用,将在下章介绍 jQuery 中的 Sizzle 选择器。通过源码,可以发现:
jQuery.find = function Sizzle(){...} jQuery.fn.find = function(selector){ ... //引用 jQuery.find jQuery.find() ... }
衍生的函数
init 函数仍然调用了不少 jQuery 或 jQuery.fn
的函数,下面来逐个分析。
jQuery.merge
这个函数通过名字,就知道它是用来干什么的,合并。
jQuery.merge = function (first, second) { var len = +second.length, j = 0, i = first.length; for (; j < len; j++) { first[i++] = second[j]; } first.length = i; return first; }
这样子就可以对类似于数组且有 length 参数的类型进行合并,我感觉主要还是为了方便对 jQuery 对象的合并,因为 jQuery 对象就是有 length 的。
jQuery.parseHTML
这个函数也非常有意思,就是将一串 HTML 字符串转成 DOM 对象。
首先函数接受三个参数,第一个参数 data 即为 html 字符串,第二个参数是 document 对象,但要考虑到浏览器的兼容性,第三个参数 keepScripts 是为了删除节点里所有的 script tags,但在 parseHTML 里面没有体现,主要还是给 buildFragment 当作参数。
总之返回的对象,是一个 DOM 数组或空数组。
jQuery.parseHTML = function (data, context, keepScripts) { if (typeof data !== "string") { return []; } // 平移参数 if (typeof context === "boolean") { keepScripts = context; context = false; } var base, parsed, scripts; if (!context) { // 下面这段话的意思就是在 context 缺失的情况下,建立一个 document 对象 if (support.createHTMLDocument) { context = document.implementation.createHTMLDocument(""); base = context.createElement("base"); base.href = document.location.href; context.head.appendChild(base); } else { context = document; } } // 用来解析 parsed,比如对 "<p></p>" 的处理结果 parsed:["<p></p>", "p"] // parsed[1] = "p" parsed = rsingleTag.exec(data); scripts = !keepScripts && []; // Single tag if (parsed) { return [context.createElement(parsed[1])]; } // 见下方解释 parsed = buildFragment([data], context, scripts); if (scripts && scripts.length) { jQuery(scripts).remove(); } return jQuery.merge([], parsed.childNodes); }
buildFragment 函数主要是用来建立一个包含子节点的 fragment 对象,用于频发操作的添加删除节点。parsed = buildFragment([data], context, scripts);
建立好一个 fragment 对象,用 parsed.childNodes
来获取这些 data 对应的 HTML。
jQueyr.makeArray
jQuery 里面的函数调用,真的是一层接一层,虽然有时候光靠函数名,就能知道这函数的作用,但其中思考之逻辑还是挺参考意义的。
jQuery.makeArray = function (arr, results) { var ret = results || []; if (arr != null) { if (isArrayLike(Object(arr))) { jQuery.merge(ret, typeof arr === "string" ? [arr] : arr); } else { push.call(ret, arr); } } return ret; }
makeArray 把左边的数组或字符串并入到右边的数组或一个新数组,其中又间接的引用 jQuery.merge
函数。
接下来是着 isArrayLike 函数,可能需要考虑多方面的因素,比如兼容浏览器等,就有了下面这一长串:
function isArrayLike(obj) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type(obj); if (type === "function" || jQuery.isWindow(obj)) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj; }
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the use of init constructor in 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

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

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

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: <

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

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:

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute
