jQuery-1.9.1 Source Analysis Series (ii) jquery Selector

Source: Internet
Author: User

1. Selector structure

jquery selector can be divided into several blocks according to the source code.

Init:function (selector, context, rootjquery) {

...

HANDLE: $ (""), $ (null), $ (undefined), $ (false)

...

Handle HTML Strings

if (typeof selector = = = = "string") {

...

HANDLE: $ (domelement)

} else if (Selector.nodetype) {

...

HANDLE: $ (function)

} else if (Jquery.isfunction (selector)) {

...

}

HANDLE: $ ($ ...)

if (selector.selector!== undefined) {

...

}

return Jquery.makearray (selector, this);

}

As you can see, jquery accepts parameters in the same way ("/null/undefined/false"), (string, context, Rootjquery), (domelement), (function), ($ ...). In addition to the case where the first argument is a string, the other is relatively simple.

$ (""/null/undefined/false) return directly

HANDLE: $ (""), $ (null), $ (undefined), $ (false)

if (!selector) {

return this;

}

$ (DomElement) converts a DOM object to a pseudo-array to return

HANDLE: $ (domelement)
else if (Selector.nodetype) {
This.context = this[0] = selector;
This.length = 1;
return this;

}

$ (function) equivalent to Jquery.ready (function)

HANDLE: $ (function)
} else if (Jquery.isfunction (selector)) {
return Rootjquery.ready (selector);
}

$($...) Wraps the result of the parameter execution (also a jquery instance) to this return

HANDLE: $ ($ ...)
if (selector.selector!== undefined) {
This.selector = Selector.selector;
This.context = Selector.context;
}

return Jquery.makearray (selector, this);

Next point : When jquery passes the first argument is a string

2. jquery Selector Core-Selector is string $ (string[,xxx]) the first few regular knowledge must be required:

Test method:

Regexpobject.test (String) is used to detect whether a string matches a pattern.

Returns trueif the string contains text that matches Regexpobject, otherwise false.

Match method:

Stringobject.match (Searchvalue | regexp) can retrieve the specified value within a string, or find a match for one or more regular expressions. The method is similar to IndexOf () and lastIndexOf (), but it returns the specified value instead of the position of the string.

The match method retrieves the string stringobject to find one or more text that matches the regexp. The behavior of this method depends to a large extent on whether RegExp has a flag g.

If RegExp does not have a flag G, then the match () method can only perform a match in Stringobject. If no matching text is found, match () returns null. Otherwise, it returns an array that holds information about the matching text it finds. The No. 0 element of the array holds the matching text , while the rest of the elements hold the text that matches the subexpression of the regular expression . In addition to these regular array elements, the returned array contains two object properties. The index property declares the position of the starting character of the matching text in Stringobject, and theinput property declares a reference to Stringobject.

If RegExp has the flag G, the match () method performs a global retrieval and finds all matching substrings in the stringobject. If no matching substring is found, nullis returned. If one or more matching substrings are found, an array is returned. However, the contents of the array returned by the global match are very different from the former, and its array elements hold all the matching substrings in the stringobject, and there is no index attribute or input property .

Note : In global retrieval mode, match () does not provide information about the text that matches the subexpression, nor does it declare the location of each matched substring. If you need these globally retrieved information, you can use Regexp.exec ().

Exec method:

Regexpobject.exec (String) returns an array that holds the results of the match . If no match is found, the return value is null.

The No. 0 element of this array is the text that matches the regular expression , and the 1th element is the text (if any) that matches the 1th sub-expression of Regexpobject, and the 2nd element is the 2nd representation of the Regexpobject Matched text (if any), and so on. In addition to the array element and the length property, the Exec () method returns two properties. The Index property declares the position of the first character of the matched text . The input property holds the string that was retrieved. We can see that when calling the Exec () method of a non-global REGEXP object, the returned array is the same as the array returned by the calling method String.match () .

However, when Regexpobject is a global regular expression, the behavior of exec () is slightly more complex. It will begin retrieving string strings at the character specified by the LastIndex property of Regexpobject. When exec () finds text that matches the expression, it sets the Regexpobject LastIndex property to the next position of the last character of the matched text after the match. This means that you can iterate through all the matching text in a string by calling the Exec () method repeatedly. When exec () can no longer find a matching text, it returns null and resets the LastIndex property to 0.

Important: If you want to start retrieving a new string after you have completed a pattern match in a string, you must manually reset the LastIndex property to 0.

Tip: Note that exec () adds complete details to the array it returns, regardless of whether the regexpobject is a global mode. This is where EXEC () differs from String.match (), which returns much less information in global mode. So we can say that calling the Exec () method repeatedly in a loop is the only way to get complete pattern matching information for the global schema.

eg

var str = "Visit w3school sfsffs test W3school w3school";

var Patt = new RegExp (/(W3) (School)/);

var result = patt.exec (str);//["W3school", "W3", "School"]

Result.index;//6

result.input;//"Visit w3school sfsffs test W3school W3school"

Patt = new RegExp (/(W3) (School)/g);

result = Patt.exec (str);//["W3school", "W3", "School"]

Result.index;//6

Patt.lastindex;//14

result = Patt.exec (str);//["W3school", "W3", "School"]

Result.index;//27

Patt.lastindex;//35

jquery Selector The first parameter is a string of source code analysis

Note : the Stringobject.charat (index) method returns the character at the specified position

First, the overall view of the source code in thin analysis

if (Selector.charat (0) = = = "<" && Selector.charat (selector.length-1) = = = ">" && selector.length >= 3) {

Match HTML tags

Match = [NULL, selector, NULL];

} else {

rquickexpr =/^ (?:( <[\w\W]+>) [^>]*|# ([\w-]*)] $/,

Match HTML tag + string (can be a null character) or #+ string (can be a null character)

Match = rquickexpr.exec (selector);

}

Match the HTML or ensure that the context is not specified for the selector as #id

Because when the selector is #id, match = ["#id", Undefined, "id"],match[1] is undefined

if (Match && (match[1] | |!context)) {

HANDLE: $ (HTML), $ (array); The selector is an HTML string that parses the string into an array of DOM elements to return

if (Match[1]) {

...

}

HANDLE: $ (#id); selector is ID

else {

...

}

HANDLE: $ (expr, $ (...)); The context of the selector is not the case for a jquery object, such as $ ("P"), $ ("P", $ (". Test")): Look up the P tag element under $ (". Test")

} else if (!context | | context.jquery) {

Return (Context | | rootjquery). FIND (selector);

HANDLE: $ (expr, context); the context of the selector is a real contextual environment, such as $ ("P", ". Test"): finds the P tag element under class. Test, equivalent to $ (context). Find (Expr )

} else {

return This.constructor (context). Find (selector);

}

Where we use the Find function to parse him in the back, now we just need to know that he is looking for a subordinate node. Next the main analysis of the selector for the ID and HTML string case

A. Selector is an HTML string

First parse the HTML string into a collection of DOM nodes, and then merge it with the current jquery instance

Jquery.merge (This, jquery.parsehtml (
MATCH[1],
Context && Context.nodetype? context.ownerdocument | | Context:document,
True
) );

For example: $ ("<span><p></p></span><div></div>") combined result is

  

It then determines whether the HTML string is a separate label and whether the latter argument is an object (the props object). If the condition is met, the property of the object is added to the Label property (attribute). It is particularly important to note that if a property name for the props object (assuming fncname) is the function name of the DOM collection object that was just collected (actually, the jquery object), Pass the value of the Fncname property of the props object as an argument to the Fncname function in the DOM collection object and execute it

Rsingletag =/^< (\w+) \s*\/?> (?: <\/\1>|) $/

HANDLE: $ (HTML, props)

if (Rsingletag.test (match[1]) && jquery.isplainobject (context)) {
For (match in context) {
The property of the context is the function of the execution
if (Jquery.isfunction (this[match])) {
this[Match] (context[match]);

Other conditions set T as attributes
} else {
This.attr (match, context[match]);
}
}
}

Finally returns the processed DOM collection object

return this;

Full source

HANDLE: $ (HTML), $ (array)

if (Match[1]) {
Context = Context instanceof JQuery? CONTEXT[0]: Context;

Jquery.merge (This, jquery.parsehtml (
MATCH[1],
Context && Context.nodetype? context.ownerdocument | | Context:document,
True
) );

HANDLE: $ (HTML, props)
if (Rsingletag.test (match[1]) && jquery.isplainobject (context)) {
For (match in context) {
if (Jquery.isfunction (this[match])) {
this[Match] (context[match]);

}else {
This.attr (match, context[match]);
}
}
}
return this;
}

B. Selector as ID

If the selector is an ID, it is directly obtained directly using the native document.getElementById.

The only thing that needs to be done is compatibility as a challenge. The node returned by Blackberry 4.6 may no longer be on the DOM (cached), so it is necessary to determine if the node exists and its parent node exists;

if (Elem && elem.parentnode)

IE and opera sometimes use the name attribute instead of the id attribute, and the returned result may not be what we expect, and this time it needs to be compatible. Use Find lookup to replace

if (elem.id!== match[2]) {

return Rootjquery.find (selector);
}

Adds a compatible node element to this and returns.

Full Source:

HANDLE: $ (#id)

else {
Elem = document.getElementById (match[2]);

Blackberry 4.6 The returned node may no longer be in the document #6963
if (Elem && elem.parentnode) {
IE and Opera sometimes use the name substitution ID to query for processing that results in the wrong result
if (elem.id!== match[2]) {
return Rootjquery.find (selector);
}

This.length = 1;
This[0] = Elem;
}

This.context = document;
This.selector = selector;
return this;
}

jQuery-1.9.1 Source Analysis Series (ii) jQuery selector

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.