目錄
jQuery之$()
$()的定義
init方法的定義
selector是字串
selector是DOM元素
selector是函數
修改init的原型
首頁 web前端 js教程 jQuery中$()函數的使用方法

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

Jul 21, 2018 am 10:56 AM
javascript jquery 原始碼分析

這篇文章要跟大家分享的是關於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

熱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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

jQuery中如何使用PUT請求方式? jQuery中如何使用PUT請求方式? Feb 28, 2024 pm 03:12 PM

jQuery中如何使用PUT請求方式?在jQuery中,發送PUT請求的方法與發送其他類型的請求類似,但需要注意一些細節和參數設定。 PUT請求通常用於更新資源,例如更新資料庫中的資料或更新伺服器上的檔案。以下是在jQuery中使用PUT請求方式的具體程式碼範例。首先,確保引入了jQuery庫文件,然後可以透過以下方式發送PUT請求:$.ajax({u

jQuery小技巧:快速修改頁面所有a標籤的文本 jQuery小技巧:快速修改頁面所有a標籤的文本 Feb 28, 2024 pm 09:06 PM

標題:jQuery小技巧:快速修改頁面所有a標籤的文字在網頁開發中,我們經常需要對頁面中的元素進行修改和操作。使用jQuery時,有時候需要一次修改頁面中所有a標籤的文字內容,這樣可以節省時間和精力。以下將介紹如何使用jQuery快速修改頁面所有a標籤的文本,同時給出具體的程式碼範例。首先,我們需要引入jQuery庫文件,確保在頁面中引入了以下程式碼:&lt

jQuery如何移除元素的height屬性? jQuery如何移除元素的height屬性? Feb 28, 2024 am 08:39 AM

jQuery如何移除元素的height屬性?在前端開發中,經常會遇到需要操作元素的高度屬性的需求。有時候,我們可能需要動態改變元素的高度,而有時候又需要移除元素的高度屬性。本文將介紹如何使用jQuery來移除元素的高度屬性,並提供具體的程式碼範例。在使用jQuery操作高度屬性之前,我們首先需要了解CSS中的height屬性。 height屬性用於設定元素的高度

使用jQuery修改所有a標籤的文字內容 使用jQuery修改所有a標籤的文字內容 Feb 28, 2024 pm 05:42 PM

標題:使用jQuery修改所有a標籤的文字內容jQuery是一款受歡迎的JavaScript庫,被廣泛用於處理DOM操作。在網頁開發中,經常會遇到需要修改頁面上連結標籤(a標籤)的文字內容的需求。本文將介紹如何使用jQuery來實現這個目標,並提供具體的程式碼範例。首先,我們需要在頁面中引入jQuery庫。在HTML檔案中加入以下程式碼:

了解jQuery中eq的作用及應用場景 了解jQuery中eq的作用及應用場景 Feb 28, 2024 pm 01:15 PM

jQuery是一種流行的JavaScript庫,被廣泛用於處理網頁中的DOM操作和事件處理。在jQuery中,eq()方法是用來選擇指定索引位置的元素的方法,具體使用方法和應用場景如下。在jQuery中,eq()方法選擇指定索引位置的元素。索引位置從0開始計數,即第一個元素的索引是0,第二個元素的索引是1,依此類推。 eq()方法的語法如下:$("s

如何判斷jQuery元素是否具有特定屬性? 如何判斷jQuery元素是否具有特定屬性? Feb 29, 2024 am 09:03 AM

如何判斷jQuery元素是否具有特定屬性?在使用jQuery操作DOM元素時,常會遇到需要判斷元素是否具有某個特定屬性的情況。在這種情況下,我們可以藉助jQuery提供的方法來輕鬆實現這項功能。以下將介紹兩種常用的方法來判斷一個jQuery元素是否具有特定屬性,並附上具體的程式碼範例。方法一:使用attr()方法和typeof運算子//判斷元素是否具有特定屬

使用jQuery為表格新增一行的方法介紹 使用jQuery為表格新增一行的方法介紹 Feb 29, 2024 am 08:12 AM

jQuery是一個受歡迎的JavaScript函式庫,廣泛用於網頁開發。在網頁開發過程中,經常需要透過JavaScript動態地在表格中新增一行。本文將介紹如何使用jQuery為表格新增一行,並提供具體的程式碼範例。首先,我們需要在HTML頁面中引入jQuery函式庫。可以透過以下程式碼在標籤中引入jQuery庫:

jQuery中如何檢查元素是否包含某個屬性值? jQuery中如何檢查元素是否包含某個屬性值? Feb 28, 2024 pm 02:54 PM

在jQuery中,我們經常需要檢查元素是否包含特定的屬性值。這樣做可以幫助我們根據元素上的屬性值執行對應的操作。在本文中,我將介紹如何使用jQuery來檢查元素是否包含某個屬性值,並提供具體的程式碼範例。首先,讓我們先了解jQuery中的一些常用方法來操作元素的屬性:.attr():用來取得或設定元素的屬性值。 .prop():用於取得或設定元素的屬性值

See all articles