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!

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.
