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 ); }
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 // 或 $(#id) if ( typeof selector === "string" ) { if ( selector[ 0 ] === "" && 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 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;
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.
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software