>  기사  >  웹 프론트엔드  >  jQuery에서 $() 함수를 사용하는 방법

jQuery에서 $() 함수를 사용하는 방법

不言
不言원래의
2018-07-21 10:56:053632검색

이 글은 jQuery에서 $() 함수를 사용하는 방법을 공유합니다. 내용이 매우 좋습니다. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

$() of jQuery

일반적으로 jQuery를 사용할 때 항상 $()를 사용합니다. $는 전역 jQuery를 가리킵니다. 그래서 사실 jQuery()가 호출되고 결과는 jq 객체가 반환되는데, 우리가 이를 사용할 때는 객체를 생성하기 위해 new를 사용할 필요가 없습니다. 이므로 $( )가 팩토리 함수라고 추측할 수 있습니다. $()$指向全局的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

$()

jQuery()의 정의는 src/core.js에 정의되어 있습니다. 메소드 new jQuery()는 루프에 갇혀 있으므로 인스턴스 구성을 돕기 위해 init()가 호출됩니다. jQuery.fn/src/core.jsjQuery.prototype을 가리킨다는 점은 언급할 가치가 있습니다.

rrreee

init 메소드 정의


jQuery.fn.init()src/core/init.js에 정의되어 있습니다. 이 메소드는 selector, context, root 세 개의 매개변수를 허용합니다. 메소드 내부에서는 먼저 매개변수가 없는지 확인하고 false를 반환합니다. rrreee

selector는 문자열입니다

selector가 비어 있지 않으면 먼저 selector가 html로 구분되는 문자열인 경우를 처리하세요. string, $(selector), $(expr, $(...))$(expr, context). selector가 문자열 유형인 경우, 수신 문자열을 기반으로 생성된 dom 노드를 반환합니다. 먼저 일반 일치를 사용하여 html 문자열 또는 ID를 찾습니다. 일치하는 결과가 비어 있지 않고 일치하는 문자열이 있거나 컨텍스트가 비어 있는 경우 selector가 html 문자열이거나 selector가 id 선택기이고 검색 컨텍스트는 제한되지 않습니다. HTML 문자열을 처리할 때 먼저 생성된 노드가 삽입될 문서(예: context 매개변수)를 결정합니다. 기본값은 jQuery 문서를 로드하고 $.parseHTML()dom 노드를 생성하여 <code>this에 추가합니다. context가 객체인 경우 $(html, props)에 대한 호출입니다. , 속성 또는 메소드가 dom에 마운트되고 생성된 jq 객체를 반환합니다. $(#id)에 대한 호출이 일치하고 context가 비어 있으면 document.getElementById가 직접 호출되어 요소를 찾습니다. 요소가 존재하는 경우 this[0]는 해당 요소를 가리키고 검색 결과를 반환합니다. selector가 id 선택기가 아니거나 context가 비어 있지 않으면 find를 호출하여 찾으십시오. context인 경우 비어 있지 않으면 컨텍스트에서 검색을 시작하고, 그렇지 않으면 전역적으로 검색하고 검색 결과를 반환 값으로 사용합니다.

selector는 DOM 요소입니다.

그런 다음 들어오는 매개변수가 Dom 요소인 경우를 처리합니다. this[0]를 Dom 요소로 지정하고 jq 객체의 길이를 1로 설정한 다음 this를 반환합니다.

selector는 함수입니다

마지막으로 $(function(){})를 처리합니다. ready가 존재하는 경우 수신 함수 호출 를 호출합니다. 준비(f())이고, 그렇지 않으면 jQuery를 전달하고, 함수를 직접 호출하고, makeArray를 호출하고, 결과를 반환 값으로 사용합니다.

init 프로토타입 수정

rrreee
프로토타입에서 init 메서드를 정의한 다음 init 프로토타입을 jQuery 프로토타입으로 지정합니다. , 생성된 인스턴스의 프로토타입은 jQuery.fn이 아닌 init.prototype이며 실제로는 jQuery의 인스턴스가 아닌 init의 인스턴스로 정의된 대로 호출할 수 없습니다. core.js jQuery.fn의 다양한 변수 및 메서드.
관련 권장사항:
🎜🎜🎜Ajax를 통해 Execl 파일 다운로드를 요청하는 방법🎜🎜🎜🎜🎜slice를 사용하여 JS에서 배열 메소드를 캡슐화🎜🎜🎜🎜🎜

위 내용은 jQuery에서 $() 함수를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.