Home > Web Front-end > JS Tutorial > body text

How to use the $() function in jQuery

不言
Release: 2018-07-21 10:56:05
Original
3704 people have browsed it

This article shares with you how to use the $() function in jQuery. The content is very good. Friends in need can refer to it. I hope it can help everyone.

jQuery's $()

Generally when we use jQuery, we use $(), $ points to the global jQuery, so jQuery() is actually called, and the result is to return a jq object, but when we use it, we do not need to use new to create the object, so we can speculate$() is a factory function. The definition of

$()

jQuery() is defined in src/core.js, if called in this method return new jQuery() will fall into a loop, so call init() to help construct the instance. It is worth mentioning that jQuery.fn points to jQuery.prototype in /src/core.js.

    // 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 );
    }
Copy after login

The definition of init method

jQuery.fn.init() is defined in src/core/init.js. The method accepts three parameters selector, context, root. Inside the method, first determine whether there are parameters. If there are no parameters, it will return 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 );
    };
Copy after login

selector is a string

If selector is not empty, first handle the case where selector is a string, divided into html string, There are four types: $(selector), $(expr, $(...)) and $(expr, context). If selector is a string type, return the generated dom node based on the incoming string. During processing, first use regular matching to find the html string or id. If the matching result is non-empty and there is a matching string or the context is empty, it means selctor is an html string or selector is an id selector and the search context is not qualified. When processing html strings, first determine which document the generated node is to be inserted into (that is, the context parameter). The default is to load the jQuery document and call $.parseHTML() Generate dom nodes and add them to this; if context is an object, it is a call to $(html, props) to mount attributes or methods to dom on, return the generated jq object. If the call to $(#id) is matched and context is empty, document.getElementById is called directly to find the element. If the element exists, this [0] points to the element and returns the search result.

If selector is not an id selector or context is not empty, call find to find, if context is not empty , then start the search from context, otherwise search globally and use the search result as the return value.

selector is a DOM element

Then handle the case where the incoming parameter is a Dom element. Point this[0] to the Dom element, set the jq object length to 1, and return this.

selector is the function

that is finally processed $(function(){}), if ready exists, the incoming function call is called ready(f()), otherwise pass in jQuery, call the function directly, call makeArray, and use the result as the return value.

Modify the prototype of init

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

Define the method on the prototypeinit, and then point the prototype of init to the prototype of jQuery. If you do not do this, the created instance will The prototype is init.prototype, not jQuery.fn. It is actually an instance of init rather than an instance of jQuery. It cannot be called and is defined in core.js. Various variables and methods on ##jQuery.fn.

Related recommendations:


How to request to download an Execl file through Ajax

Use slice to encapsulate arrays in JS method

The above is the detailed content of How to use the $() function in jQuery. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template