Home Web Front-end JS Tutorial jQuery selector source code interpretation (5): parsing process of tokenize_jquery

jQuery selector source code interpretation (5): parsing process of tokenize_jquery

May 16, 2016 pm 04:06 PM
jquery Source code interpretation Selector

The following analysis is based on jQuery-1.10.2.js version.

The following will take $("div:not(.class:contain('span')):eq(3)") as an example to explain how the tokenize and preFilter codes are coordinated to complete the parsing. If you want to know the detailed explanation of each line of code of the tokenize method and preFilter class, please refer to the following two articles:

http://www.jb51.net/article/63155.htm
http://www.jb51.net/article/63163.htm

The following is the source code of the tokenize method. For simplicity, I have removed all the codes related to caching, comma matching and relational character matching, leaving only the core code related to the current example. The code that was removed is very simple. If necessary, you can read the above article.

In addition, the code is written above the description text.

Copy code The code is as follows:

function tokenize(selector, parseOnly) {
var matched, match, tokens, type, soFar, groups, preFilters;

soFar = selector;
groups = [];
preFilters = Expr.preFilter;

while (soFar) {
if (!matched) {
groups.push(tokens = []);
}

matched = false;

for (type in Expr.filter) {
If ((match = matchExpr[type].exec(soFar))
&& (!preFilters[type] || (match = preFilters[type]
(match)))) {
Matched = match.shift();
tokens.push({
Value: matched,
Type : type,
       matches: match
});
SoFar = soFar.slice(matched.length);
}
}

if (!matched) {
Break;
}
}

return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) :
tokenCache(selector, groups).slice(0);
}


First, tokenize is called for the first time by the select method during jQuery execution, and "div:not(.class:contain('span')):eq(3)" is passed into the method as the selector parameter.
Copy code The code is as follows:

soFar = selector;

soFar = "div:not(.class:contain('span')):eq(3)"
When entering the while loop for the first time, since matched has not been assigned a value, the following statement body in the if is executed. This statement will initialize the tokens variable and push tokens into the groups array.

Copy code The code is as follows:

groups.push(tokens = []);

After that, enter the for statement.

The first for loop: take the first element "TAG" from Expr.filter and assign it to the type variable, and execute the loop body code.

Copy code The code is as follows:

If ((match = matchExpr[type].exec(soFar))
&& (!preFilters[type] || (match = preFilters[type]
(match)))) {

The execution result of match = matchExpr[type].exec(soFar) is as follows:

match =["div", "div"]

The first selector in the example is div, which matches the regular expression of matchExpr["TAG"], and preFilters["TAG"] does not exist, so the statement body within the if is executed.

Copy code The code is as follows:

matched = match.shift();

Remove the first element div in the match and assign the element to the matched variable. At this time, matched="div", match = ["div"]

Copy code The code is as follows:

tokens.push({
Value: matched,
Type : type,
       matches: match
}

Create a new object { value: "div", type: "TAG", matches: ["div"] } and push the object into the tokens array.

Copy code The code is as follows:

SoFar = soFar.slice(matched.length);

The soFar variable deletes the div. At this time, soFar=":not(.class:contain('span')):eq(3)"
The second for loop: Take the second element "CLASS" from Expr.filter and assign it to the type variable, and execute the loop body code.

Copy code The code is as follows:

If ((match = matchExpr[type].exec(soFar))
&& (!preFilters[type] || (match = preFilters[type]
(match)))) {

Since the current soFar=":not(.class:contain('span')):eq(3)" does not match the regular expression of CLASS type, this loop ends.
The third for loop: Take the third element "ATTR" from Expr.filter and assign it to the type variable, and execute the loop body code.
Similarly, since the current remaining selectors are not attribute selectors, this cycle ends.

The fourth for loop: Take the fourth element "CHILD" from Expr.filter and assign it to the type variable, and execute the loop body code.
Similarly, since the current remaining selector is not a CHILD selector, this cycle ends.

The fifth for loop: Take the fifth element "PSEUDO" from Expr.filter and assign it to the type variable, and execute the loop body code.

Copy code The code is as follows:

If ((match = matchExpr[type].exec(soFar))
&& (!preFilters[type] || (match = preFilters[type]
(match)))) {

The execution result of match = matchExpr[type].exec(soFar) is as follows:
[":not(.class:contain('span')):eq(3)", "not", ".class:contain('span')):eq(3", undefined, undefined, undefined, undefined , undefined, undefined, undefined, undefined]

Since preFilters["PSEUDO"] exists, the following code is executed:

Copy code The code is as follows:

match = preFilters[type](match)

preFilters["PSEUDO"] code is as follows:

Copy code The code is as follows:

"PSEUDO" : function(match) {
var excess, unquoted = !match[5] && match[2];

if (matchExpr["CHILD"].test(match[0])) {
return null;
}

if (match[3] && match[4] !== undefined) {
match[2] = match[4];
} else if (unquoted
&& rpseudo.test(unquoted)
&& (excess = tokenize(unquoted, true))
&& (excess = unquoted.indexOf(")", unquoted.length
- excess)
- unquoted.length)) {

match[0] = match[0].slice(0, excess);
match[2] = unquoted.slice(0, excess);
}

return match.slice(0, 3);
}

The match parameter passed in is equal to:

Copy code The code is as follows:

[":not(.class:contain('span')):eq(3)", "not", ".class:contain('span')):eq(3", undefined, undefined, undefined, undefined , undefined

Copy code The code is as follows:

unquoted = !match[5] && match[2]

unquoted = ".class:contain('span')):eq(3"

Copy code The code is as follows:

if (matchExpr["CHILD"].test(match[0])) {
Return null;
}

match[0] = ":not(.class:contain('span')):eq(3)", does not match the matchExpr["CHILD"] regular expression, and does not execute the return null statement.

Copy code The code is as follows:

if (match[3] && match[4] !== undefined) {
Match[2] = match[4];
}

Since match[3] and match[4] are both equal to undefined, the else statement body is executed.

Copy code The code is as follows:

else if (unquoted
              && rpseudo.test(unquoted)  
​​​​&& (excess = tokenize(unquoted, true))
​​​​&& (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)

At this time, unquoted = ".class:contain('span')):eq(3" is true, and because unquoted contains:contain('span'), it matches the regular expression rpseudo, so rpseudo. test(unquoted) is true, and then call tokenize again to parse unquoted again, as follows:

Copy code The code is as follows:

excess = tokenize(unquoted, true)

When calling the tokenize function this time, the incoming selector parameter is equal to ".class:contain('span')):eq(3", and parseOnly is equal to true. The execution process in the function body is as follows:

Copy code The code is as follows:

soFar = selector;

soFar = ".class:contain('span')):eq(3"
When entering the while loop for the first time, since matched has not been assigned a value, the following statement body in the if is executed. This statement will initialize the tokens variable and push tokens into the groups array.

Copy code The code is as follows:

groups.push(tokens = []);
After

, enter the for statement.

The first for loop: take the first element "TAG" from Expr.filter and assign it to the type variable, and execute the loop body code.

Copy code The code is as follows:

if ((match = matchExpr[type].exec(soFar))
          && (!preFilters[type] || (match = preFilters[type]
(match)))) {

Since the current remaining selector is not a TAG selector, this cycle ends.
The second for loop: Take the second element "CLASS" from Expr.filter and assign it to the type variable, and execute the loop body code.

The execution result of match = matchExpr[type].exec(soFar) is as follows:

match = ["class" , "class"]

Since preFilters["CLASS"] does not exist, the statement body within the if is executed.

Copy code The code is as follows:

matched = match.shift();

Remove the first element class in match and assign the element to the matched variable. At this time, matched="class", match = ["class"]

Copy code The code is as follows:

tokens.push({
value : matched,
Type : type,
matches : match
}

Create a new object { value: "class", type: "CLASS", matches: ["class"] } and push the object into the tokens array.

Copy code The code is as follows:

soFar = soFar.slice(matched.length);

The soFar variable deletes the class. At this time, soFar = ":contain('span')):eq(3"
The third for loop: Take the third element "ATTR" from Expr.filter and assign it to the type variable, and execute the loop body code.
Similarly, since the current remaining selectors are not attribute selectors, this cycle ends.

The fourth for loop: Take the fourth element "CHILD" from Expr.filter and assign it to the type variable, and execute the loop body code.
Similarly, since the current remaining selector is not a CHILD selector, this cycle ends.

The fifth for loop: Take the fifth element "PSEUDO" from Expr.filter and assign it to the type variable, and execute the loop body code.

Copy code The code is as follows:

if ((match = matchExpr[type].exec(soFar))
          && (!preFilters[type] || (match = preFilters[type]
(match)))) {

The execution result of match = matchExpr[type].exec(soFar) is as follows:
[":contain('span')", "contain", "'span'", "'", "span", undefined, undefined, undefined, undefined, undefined, undefined]

Since preFilters["PSEUDO"] exists, the following code is executed:

Copy code The code is as follows:

match = preFilters[type](match)

The preFilters["PSEUDO"] code is shown above and will not be listed here.

Copy code The code is as follows:

"PSEUDO" : function(match) {
var excess, unquoted = !match[5] && match[2];

If (matchExpr["CHILD"].test(match[0])) {
         return null;                                }  

If (match[3] && match[4] !== undefined) {
         match[2] = match[4]; 
} else if (unquoted
                                                                                                                                                                                                                                     && (excess = tokenize(unquoted, true))                                                                              && (excess = unquoted.indexOf(")", unquoted.length 
                                                                                                                                                                                                                                           - excess)
- unquoted.length)) {

         match[0] = match[0].slice(0, excess);
         match[2] = unquoted.slice(0, excess);
}  

Return match.slice(0, 3);
}



The incoming match parameter is equal to:
[":contain('span')", "contain", "'span'", "'", "span", undefined, undefined, undefined, undefined, undefined, undefined]


Copy code The code is as follows: unquoted = !match[5] && match[2];


unquoted = "span"


Copy code The code is as follows: if (matchExpr["CHILD"].test(match[0])) {
return null;
}

Because ":contain('span')" does not match the matchExpr["CHILD"] regular expression, the internal statement body is not executed.

Copy code The code is as follows:

if (match[3] && match[4] !== undefined) {
match[2] = match[4];
}

Since match[3] = "'" and match[4] ="span", the internal if statement body is executed and "span" is assigned to match[2]

Copy code The code is as follows:

return match.slice(0, 3);

Returns a copy of the first three elements of match
At this time, return to the for loop of the tokenize method to continue execution. At this time, the values ​​of each variable are as follows:

match = [":contain('span')", "contain", "span"]

soFar = ":contain('span')):eq(3"

Copy code The code is as follows:

matched = match.shift();

Remove ":contain('span')" from the match array and assign it to the matched variable

Copy code The code is as follows:

tokens.push({
value : matched,
Type : type,
matches : match
}


Create a new object { value:
":contain('span')", type:"PSEUDO", matches: ["contain", "span"] }, and push the object into the tokens array.

Copy code The code is as follows:

soFar = soFar.slice(matched.length);

The soFar variable deletes ":contain('span')". At this time, soFar="):eq(3)", after that, until the for loop ends and the while loop is executed again, there is no valid selector. So exit the while loop.

Copy code The code is as follows:

return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) :
tokenCache(selector, groups).slice(0);

Since parseOnly = true at this time, the length of soFar at this time is returned, 6, and the code of preFilters["PSEUDO"] continues to be executed

Copy code The code is as follows:

else if (unquoted
              && rpseudo.test(unquoted)  
​​​​&& (excess = tokenize(unquoted, true))
​​​​&& (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)

Assign 6 to the excess variable, and then the code

Copy code The code is as follows:

excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length

Calculate: not selector end position (i.e. right bracket position) 22

Copy code The code is as follows:

match[0] = match[0].slice(0, excess);
match[2] = unquoted.slice(0, excess);

Calculate the complete :not selector string (match[0]) and the string in its brackets (match[2]) respectively, which are equal to:

match[0] = ":not(.class:contain('span'))"

match[2] = ".class:contain('span')"

Copy code The code is as follows:

return match.slice(0, 3);

Returns a copy of the first three elements in match.
Return to the tokenize function, now match = [":not(.class:contain('span'))", "not", ".class:contain('span')"]

Copy code The code is as follows:

matched = match.shift();

Remove the first element ":not(.class:contain('span'))" in match and assign the element to the matched variable. At this time, matched="":not(.class:contain( 'span'))"",
match = ["not", ".class:contain('span')"]

Copy code The code is as follows:

tokens.push({
value : matched,
Type : type,
matches : match
}

Create a new object { value: ":not(.class:contain('span'))"", type: "PSEUDO", matches: ["not", ".class:contain('span') "] }, and push the object into the tokens array. At this time, tokens have two elements, namely div and not selector.

Copy code The code is as follows:

soFar = soFar.slice(matched.length);

SoFar variable deletes ":not(.class:contain('span'))". At this time, soFar=":eq(3)", after ending this for loop, return to the while loop again, the same way , to obtain the eq selector of the third element of tokens, the process is consistent with not, and I will not go into details here. The results of the final groups are as follows:
group[0][0] = {value: "div", type: "TAG", matches: ["div"] }

group[0][1] = {value: ":not(.class:contain('span'))", type: "PSEUDO", matches: ["not", ".class:contain(' span')"] }

group[0][2] = {value: ":eq(3)", type: "PSEUDO", matches: ["eq", "3"] }

Copy code The code is as follows:

return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) :
tokenCache(selector, groups).slice(0);

Since parseOnly = undefined, tokenCache(selector, groups).slice(0) is executed. This statement pushes groups into the cache and returns its copy.
From this, all the parsing is completed. Some people may ask, the second element here is not parsed out. Yes, this needs to be parsed again in actual operation. Of course, if you can save the result of the valid selector in the cache when you just parsed "class:contain('span')):eq(3", you can avoid parsing again and improve the execution speed. But this It only improves the current running speed because during execution, when ".class:contain('span')" is submitted for analysis again, it will be stored in the cache.

At this point, the entire execution process has ended.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

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

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

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

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

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: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

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:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles