jQuery源码学习笔记:jQuery.fn.init(selector,context,rootjQuery)代码详解

本文主要是介绍jQuery源码学习笔记:jQuery.fn.init(selector,context,rootjQuery)代码详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

3.1 源码

init: function( selector, context, rootjQuery ) {var match, elem, ret, doc;// Handle $(""), $(null), or $(undefined)//如果selector为空格,!selector为falseif (!selector) {//此时this为空jQuery对象return this;}// Handle $(DOMElement)//nodeType节点类型,利用是否有nodeType属性来判断是否是DOM元素if ( selector.nodeType ) {//将第一个元素和属性context指向selectorthis.context = this[0] = selector;this.length = 1;return this;}// The body element only exists once, optimize finding it//因为body只出现一次,利用!context进行优化if ( selector === "body" && !context && document.body ) {//context指向document对象this.context = document;this[0] = document.body;this.selector = selector;this.length = 1;return this;}// Handle HTML stringsif ( typeof selector === "string" ) {// Are we dealing with HTML string or an ID?//以<开头以>结尾,且长度大于等于3,这里假设是HTML片段,跳过queckExpr正则检查if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {// Assume that strings that start and end with <> are HTML and skip the regex checkmatch = [ null, selector, null ];} else {match = quickExpr.exec( selector );}// Verify a match, and that no context was specified for #idif ( match && (match[1] || !context) ) {// HANDLE: $(html) -> $(array)if ( match[1] ) {context = context instanceof jQuery ? context[0] : context;doc = ( context ? context.ownerDocument || context : document );// If a single string is passed in and it's a single tag// just do a createElement and skip the restret = rsingleTag.exec( selector );//如果是单独标签if (ret) {//如果context是普通对象if (jQuery.isPlainObject(context)) {//之所以放在数组中,是方便后面的jQuery.merge()方法调用selector = [document.createElement(ret[1])];//调用attr方法,传入参数contextjQuery.fn.attr.call( selector, context, true );} else {selector = [ doc.createElement( ret[1] ) ];}//复杂HTML的处理方法} else {ret = jQuery.buildFragment( [ match[1] ], [ doc ] );selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;}return jQuery.merge( this, selector );// HANDLE: $("#id")} else {elem = document.getElementById( match[2] );// Check parentNode to catch when Blackberry 4.6 returns// nodes that are no longer in the document #6963if ( elem && elem.parentNode ) {// Handle the case where IE and Opera return items// by name instead of ID//即使是documen.getElementById这样核心的方法也要考虑到浏览器兼容问题,可能找到的是name而不是idif ( elem.id !== match[2] ) {return rootjQuery.find( selector );}// Otherwise, we inject the element directly into the jQuery objectthis.length = 1;this[0] = elem;}this.context = document;this.selector = selector;return this;}// HANDLE: $(expr, $(...))//没有指定上下文,执行rootjQuery.find(),制定了上下文且上下文是jQuery对象,执行context.find()} else if ( !context || context.jquery ) {return ( context || rootjQuery ).find( selector );// HANDLE: $(expr, context)// (which is just equivalent to: $(context).find(expr)//如果指定了上下文,且上下文不是jQuery对象} else {//先创建一个包含context的jQuery对象,然后调用find方法return this.constructor( context ).find( selector );}// HANDLE: $(function)// Shortcut for document ready} else if ( jQuery.isFunction( selector ) ) {return rootjQuery.ready( selector );}//selector是jquery对象if ( selector.selector !== undefined ) {this.selector = selector.selector;this.context = selector.context;}//合并到当前jQuery对象return jQuery.makeArray( selector, this );},

其中里面调用的其他jQuery函数待后面再详细学习。

1、其中用到了两个正则表达式:

(1)quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;

解释:?:是非捕获组的意思,非捕获组只参与匹配,但不会把匹配到的内容捕获到组里,降低了内存的占用。

[^#<]*匹配除#<以外的任意字符,且出现0次或多次

(<[\w\W]+>):

\w表示匹配字母数字、下划线,\W正好相反,这里匹配的是以字母数字下划线作为第一个字母的一个标签,比如<div>

[^>]*匹配除>之外的所有字符,且出现0次或多次,$结束,表示结束时不能为>字符

#(\w\-]*)$  #id的匹配,id只能为字母、数字、下划线和减号

(2)rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/;

解释:^<(\w+)\s*\/?>:

^<:以<开头

(\w+):匹配的字母、数字、下划线

\s*:匹配空格符0次或多次,比如可以匹配<div  >这样的

\/?>:匹配/符号0次或1次,比如匹配<img    />这样的

(?:<\/\1>):\1表示的是前面的(),这里指的就是(\w+),比如前面是<div>,这里就要是</div>

最后的?$表示的是此元素为截止符,要么截止在</div>,要么没有就是前面的<img >或者是<img />

到此就把所有的单独的标签的情况考虑完全了。

学以致用

<script type="text/javascript">var quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/;var match = quickExpr.exec("abc<div>#id");if (match) {alert(RegExp.$1)}var match1 = rsingleTag.exec("<div></div>");if (match1) {alert(RegExp.$1);}</script>





这篇关于jQuery源码学习笔记:jQuery.fn.init(selector,context,rootjQuery)代码详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/666142

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

MySql基本查询之表的增删查改+聚合函数案例详解

《MySql基本查询之表的增删查改+聚合函数案例详解》本文详解SQL的CURD操作INSERT用于数据插入(单行/多行及冲突处理),SELECT实现数据检索(列选择、条件过滤、排序分页),UPDATE... 目录一、Create1.1 单行数据 + 全列插入1.2 多行数据 + 指定列插入1.3 插入否则更

Redis中Stream详解及应用小结

《Redis中Stream详解及应用小结》RedisStreams是Redis5.0引入的新功能,提供了一种类似于传统消息队列的机制,但具有更高的灵活性和可扩展性,本文给大家介绍Redis中Strea... 目录1. Redis Stream 概述2. Redis Stream 的基本操作2.1. XADD

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数