How to use the $() function in jQuery

不言
Release: 2018-07-21 10:56:05
Original
3589 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 globaljQuery, sojQuery()is actually called, and the result is to return a jq object, but when we use it, we do not need to usenewto create the object, so we can speculate$()is a factory function. The definition of

$()

jQuery()is defined insrc/core.js, if called in this methodreturn new jQuery()will fall into a loop, so callinit()to help construct the instance. It is worth mentioning thatjQuery.fnpoints tojQuery.prototypein/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 insrc/core/init.js. The method accepts three parametersselector, context, root. Inside the method, first determine whether there are parameters. If there are no parameters, it will returnfalse.

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

Ifselectoris not empty, first handle the case whereselectoris a string, divided into html string, There are four types:$(selector),$(expr, $(...))and$(expr, context). Ifselectoris 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 meansselctoris an html string orselectoris 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, thecontextparameter). The default is to load the jQuery document and call$.parseHTML()Generate dom nodes and add them tothis; ifcontextis 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 andcontextis empty,document.getElementByIdis called directly to find the element. If the element exists,this [0]points to the element and returns the search result.

Ifselectoris not an id selector orcontextis not empty, callfindto find, ifcontextis not empty , then start the search fromcontext, 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. Pointthis[0]to the Dom element, set the jq object length to 1, and returnthis.

selector is the function

that is finally processed$(function(){}), ifreadyexists, the incoming function callis called ready(f()), otherwise pass in jQuery, call the function directly, callmakeArray, 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 isinit.prototype, notjQuery.fn. It is actually an instance of init rather than an instance of jQuery. It cannot be called and is defined incore.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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!