搜索
首页web前端js教程jQuery中$()函数的使用方法

jQuery中$()函数的使用方法

Jul 21, 2018 am 10:56 AM
javascriptjquery源码分析

本篇文章给大家分享的是关于jQuery中$()函数的使用方法,内容很不错,有需要的朋友可以参考一下,希望可以帮助到大家。

jQuery之$()

一般我们使用jQuery的时候,都是使用$()$指向全局的jQuery,所以其实是调用了jQuery(),结果是返回一个jq对象,但我们使用时却不需使用new创建对象,所以可以推测$()是一个工厂函数。

$()的定义

jQuery()src/core.js中定义,若在该方法中调用return new jQuery()则陷入循环,所以调用init()协助构造实例。值得一提的是,jQuery.fn/src/core.js指向了jQuery.prototype

    // Define a local copy of jQuery
    jQuery = function( selector, context ) {

        // The jQuery object is actually just the init constructor 'enhanced'
        // Need init if jQuery is called (just allow error to be thrown if not included)
        return new jQuery.fn.init( selector, context );
    }

init方法的定义

jQuery.fn.init()src/core/init.js中定义。方法接受三个参数selector, context, root,在方法内部,先判断是否有参数,无参数时返回false

    init = jQuery.fn.init = function( selector, context, root ) {
        var match, elem;

        // HANDLE: $(""), $(null), $(undefined), $(false)
        if ( !selector ) {
            return this;
        }

        // Method init() accepts an alternate rootjQuery
        // so migrate can support jQuery.sub (gh-2101)
        root = root || rootjQuery;

        // Handle HTML strings
        // < xxx > 或 $(#id)
        if ( typeof selector === "string" ) {
            if ( selector[ 0 ] === "<" &&
                selector[ selector.length - 1 ] === ">" &&
                selector.length >= 3 ) {

                // Assume that strings that start and end with <> are HTML and skip the regex check
                match = [ null, selector, null ];

            } else {
                // match[1]是html字符串,match[2]是匹配元素的id
                // selector是id选择器时match[1]为undefined,match[2]是匹配元素的id
                // selector是html字符串,match[1]是html字符串,match[2]为undefined
                match = rquickExpr.exec( selector );
            }

            // Match html or make sure no context is specified for #id
            // 匹配结果非空 且 存在匹配字符串或context空时执行
            // 未为id选择器限定查找范围
            if ( match && ( match[ 1 ] || !context ) ) {

                // HANDLE: $(html) -> $(array)
                if ( match[ 1 ] ) {
                    context = context instanceof jQuery ? context[ 0 ] : context;

                    // Option to run scripts is true for back-compat
                    // Intentionally let the error be thrown if parseHTML is not present
                    // 生成dom节点并合并到this上
                    jQuery.merge( this, jQuery.parseHTML(
                        match[ 1 ],
                        context && context.nodeType ? context.ownerDocument || context : document,
                        true
                    ) );

                    // HANDLE: $(html, props)
                    // 遍历props,添加属性或方法
                    if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
                        for ( match in context ) {

                            // Properties of context are called as methods if possible
                            if ( jQuery.isFunction( this[ match ] ) ) {
                                this[ match ]( context[ match ] );

                            // ...and otherwise set as attributes
                            } else {
                                this.attr( match, context[ match ] );
                            }
                        }
                    }

                    return this;

                // HANDLE: $(#id)
                // 处理id选择器且无context
                } else {
                    elem = document.getElementById( match[ 2 ] );

                    if ( elem ) {

                        // Inject the element directly into the jQuery object
                        this[ 0 ] = elem;
                        this.length = 1;
                    }
                    return this;
                }

            // HANDLE: $(expr, $(...))
            // selector是选择器 context为undefined或context.jquery存在时执行。
            // $(#id,context)或$(.class [, context])等情况
            } else if ( !context || context.jquery ) {
                return ( context || root ).find( selector );

            // HANDLE: $(expr, context)
            // (which is just equivalent to: $(context).find(expr)
            } else {
                return this.constructor( context ).find( selector );
            }

        // HANDLE: $(DOMElement)
        // 传入DOM元素
        } else if ( selector.nodeType ) {
            this[ 0 ] = selector;
            this.length = 1;
            return this;

        // HANDLE: $(function)
        // Shortcut for document ready
        } 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 );
    };

selector是字符串

如果有selector非空,先处理selector是字符串的情况,分为html字符串、$(selector)$(expr, $(...))$(expr, context)四种。如果selector是字符串类型,根据传入的字符串返回生成的dom节点,处理时先用正则匹配,查找html字符串或id。匹配结果非空且存在匹配字符串或context空时说明selctor是html字符串或selector是id选择器且未限定查找上下文。执行处理html字符串时,先确定生成后的节点要插入的document是哪个(即context参数),默认是加载jQuery的document,调用$.parseHTML()生成dom节点并添加到this;如果context是对象,则是$(html, props)的调用,将属性或者方法挂载到dom上,返回生成的jq对象。如果匹配到$(#id)的调用且context空时,则直接调用document.getElementById查找元素,元素存在时将this[0]指向该元素,返回查找结果。

如果selector不是id选择器或context非空,调用find进行查找,如果context非空,则从context开始查找,否则全局查找,将查找结果作为返回值。

selector是DOM元素

接着处理传入参数是Dom元素的情况。将this[0]指向Dom元素,设置jq对象长度为1,并返回this

selector是函数

最后处理$(function(){}),如果存在ready则调用传入函数调用ready(f()),否则传入jQuery,直接调用函数,调用makeArray,将其结果作为返回值。

修改init的原型

init = jQuery.fn.init = function( selector, context, root ) {
    ...
    }
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

在原型上定义方法init,然后将init的原型指向jQuery的原型,如果不这么做,则创建的实例的原型是init.prototype,不是jQuery.fn,其实是init的实例而不是jQuery的实例,无法调用在core.js中定义在jQuery.fn上的各种变量和方法。

相关推荐:

通过Ajax如何请求下载Execl文件

在JS中用slice封装数组方法

以上是jQuery中$()函数的使用方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JavaScript是用C编写的吗?检查证据JavaScript是用C编写的吗?检查证据Apr 25, 2025 am 12:15 AM

是的,JavaScript的引擎核心是用C语言编写的。1)C语言提供了高效性能和底层控制,适合JavaScript引擎的开发。2)以V8引擎为例,其核心用C 编写,结合了C的效率和面向对象特性。3)JavaScript引擎的工作原理包括解析、编译和执行,C语言在这些过程中发挥关键作用。

JavaScript的角色:使网络交互和动态JavaScript的角色:使网络交互和动态Apr 24, 2025 am 12:12 AM

JavaScript是现代网站的核心,因为它增强了网页的交互性和动态性。1)它允许在不刷新页面的情况下改变内容,2)通过DOMAPI操作网页,3)支持复杂的交互效果如动画和拖放,4)优化性能和最佳实践提高用户体验。

C和JavaScript:连接解释C和JavaScript:连接解释Apr 23, 2025 am 12:07 AM

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。

从网站到应用程序:JavaScript的不同应用从网站到应用程序:JavaScript的不同应用Apr 22, 2025 am 12:02 AM

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python vs. JavaScript:比较用例和应用程序Python vs. JavaScript:比较用例和应用程序Apr 21, 2025 am 12:01 AM

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

C/C在JavaScript口译员和编译器中的作用C/C在JavaScript口译员和编译器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在行动中:现实世界中的示例和项目JavaScript在行动中:现实世界中的示例和项目Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具