How to use selector and context in jQuery object?
The two attributes of the jQuery object, selector and context, were not clear at all at first. Then I searched on Baidu and Google for a long time, but could not find the reason. Later, I found this jquery in the jQuery API document. The selector attribute and context attribute of the object. Haha~ So~ When you have free time, it is better to go through the jQuery API documentation first and get familiar with it. It is better than being like me, who is still looking for things on the Internet and still can’t find them, which is very frustrating. Yeah~ If you students who read this article still don’t know the meaning of these two attributes, then just learn it here. In fact, the biggest use of these two attributes is to write plug-ins.
The API document says:
By default, if the context parameter is not specified, $() will search for DOM elements in the current HTML document; if the context parameter is specified, such as a DOM element set or jQuery object, it will be searched in this context. After jQuery 1.3.2, the order of the elements returned is equivalent to the order in which they appear in the context.
TheContext parameter needs to be a working node object (DOM object, not jQuery object). Although passing a jQuery object can also limit the search scope, in this case, the context property of the jQuery object will become the entire Document object.
And the value of $(expression, [context]).selector is exactly expression
For example:
$("div ul").selector//值为“div ul” $("div.test").selector//值为“div.test” $("#test ul li:first").selector//值为“test ul li:first”
That is to say, what expression is, what selector is,
$(expression, [context]).context is a DOM object. Regarding this DOM object, when using different $(expression, [context]), the context object obtained is different.
Related sample code:
function( selector, context, rootjQuery ) {var match, elem, ret, doc;// Handle $(""), $(null), or $(undefined) //如果selector为空格,!selector为false if (!selector) {//此时this为空jQuery对象 return this; }// Handle $(DOMElement) //nodeType节点类型,利用是否有nodeType属性来判断是否是DOM元素 if ( selector.nodeType ) {//将第一个元素和属性context指向selector this.context = this[0] = selector;this.length = 1;return this; }// The body element only exists once, optimize finding it //因为body只出现一次,利用!context进行优化 if ( selector === "body" && !context && document.body ) {//context指向document对象 this.context = document;this[0] = document.body;this.selector = selector;this.length = 1;return this; }// Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? //以<开头以>结尾,且长度大于等于3,这里假设是HTML片段,跳过queckExpr正则检查 if ( selector.charAt(0) === "<" && selector.charAt( 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 = quickExpr.exec( selector ); }// Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) {// HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document );// If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); //如果是单独标签 if (ret) {//如果context是普通对象 if (jQuery.isPlainObject(context)) { //之所以放在数组中,是方便后面的jQuery.merge()方法调用 selector = [document.createElement(ret[1])]; //调用attr方法,传入参数context jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } //复杂HTML的处理方法 } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; }return jQuery.merge( this, selector );// HANDLE: $("#id") } else { elem = document.getElementById( match[2] );// Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) {// Handle the case where IE and Opera return items // by name instead of ID //即使是documen.getElementById这样核心的方法也要考虑到浏览器兼容问题,可能找到的是name而不是id if ( elem.id !== match[2] ) {return rootjQuery.find( selector ); }// Otherwise, we inject the element directly into the jQuery object this.length = 1;this[0] = elem; }this.context = document;this.selector = selector;return this; }// HANDLE: $(expr, $(...)) //没有指定上下文,执行rootjQuery.find(),制定了上下文且上下文是jQuery对象,执行context.find() } else if ( !context || context.jquery ) {return ( context || rootjQuery ).find( selector );// HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) //如果指定了上下文,且上下文不是jQuery对象 } else { //先创建一个包含context的jQuery对象,然后调用find方法 return this.constructor( context ).find( selector ); }// HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) {return rootjQuery.ready( selector ); } //selector是jquery对象 if ( selector.selector !== undefined ) {this.selector = selector.selector;this.context = selector.context; } //合并到当前jQuery对象 return jQuery.makeArray( selector, this ); }
The above is the detailed content of How to use selector and context in jQuery object?. For more information, please follow other related articles on the PHP Chinese website!

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.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!