Home Web Front-end JS Tutorial jQuery constructor init parameter analysis continued_jquery

jQuery constructor init parameter analysis continued_jquery

May 16, 2016 pm 03:59 PM
jquery Constructor

If the selector is another string, the situation will be more complicated

// Handle HTML strings
if ( typeof selector === "string" ) {...} 

Copy after login

Start to deal with different situations

// Are we dealing with HTML string or an ID?
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 );
}
Copy after login

If it is first judged that the first character is "<" and the last character is ">" and the length is greater than 3, it is assumed that the selector at this time is a simple html tag, such as $('

') but Remember just to assume that an "assume" like $('') will go here. Then modify the match array to [null, selector, null]. The match here is a variable declared in the init function. It is mainly used as a tool to distinguish parameter types. The possible situations will be listed later. The following is the source code. Four variables declared

init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;

Copy after login

If the if condition is not met, a regular expression will be called to get the match result. quickExpr is a variable declared in the jQuery constructor

// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(&#63;:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,

Copy after login

This regular rule is mainly to distinguish html strings and id strings. The second comment mentions that in order to avoid XSS attacks based on location.hash, # (#9521) is added to quickExpr, which means we Related explanations can be found on the jQuery official website.

First visit http://bugs.jquery.com/ and then search for the corresponding value

The execution result of quickExpr.exec(selector) can be an array. The first element of the array is the matching element, and the remaining elements are grouped matching elements. This regular expression has two groups (<[wW] >)[^>] and ([w-]*) are labels and id values. The result will eventually be given to match. Let’s analyze the various situations of match. First, a single label without regular expression is in the form of [null, selector, null], which is proved in the code below:

<!doctype html>
<html>
  <head>
   <title></title>
    <script src='jquery-1.7.1.js'></script>
  </head>
  <body>
    <div id='div'></div> 
  </body>
  <script>
    $('<div>');
  </script>
</html>
Copy after login

In html we create a jQuery object and then output the match result in the init method:

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 );
}
 console.log(match); // [null, "<div>", null];
Copy after login

Let’s modify the parameters to $(‘#div’) and then take a look at the results

Copy code The code is as follows:

["#div", undefined, "div", index: 0, input: "#div"]

There is also a special case $(‘

123') and then let’s take a look at the result

Copy code The code is as follows:

["
dewrwe", "
", undefined, index: 0, input: "
dewrwe"]

We can see that the id is always in the third element and the tag value is saved in the second element. For the last case, there is no difference from $('

') because it generates When using dom elements, the first element will not be processed. Based on this result, we can proceed to analyze the next judgment.

The following will be divided into three situations based on the match results

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

     ...

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

    ...

} else {

  ...

}

Copy after login

The condition that is met in the first case is that match must have a value. Match[1] means that the second element is the one that saves the label. It has a value or does not have a context, but it seems that there is no ID. What's the matter? In fact, it is not the case. By analyzing the match results, we can know that the second element with no value must be the result obtained by the id selector, and the id is unique, and there is no need to write a context (in fact, if the context is written, it will execute normally, but Sizzle will be used instead. It is not processed here the same as body). Okay, the first condition comes in is

1. Tag

$(‘

') $(‘
123') $(‘
23213213
')...

2. ID without context $(‘#div’)

The first condition is further subdivided internally:

// HANDLE: $(html) -> $(array)
if ( match[1] ) {

  ...

// HANDLE: $("#id")

}else{

}

Copy after login

Obviously if is used to process tags and else is used to process ids. Let’s first take a look at how tags are processed

context = context instanceof jQuery &#63; context[0] : context;
doc = ( context &#63; 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 ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
 
} else {
selector = [ doc.createElement( ret[1] ) ];
}
 
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable &#63; jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
 
return jQuery.merge( this, selector);
Copy after login

First correct the value of context. If it is a jQuery object, turn it into a dom element using the subscript method. This principle has been mentioned before, and then the doc variable is processed. If the context does not exist, assign the document value to doc. If it exists and has the ownerDocument attribute, it is a dom element. This value is still document. If it is not a dom element, such as an ordinary js object, then assign this object to the doc variable. Immediately afterwards, another regular judgment was performed on the selector. This regular rule was also declared in the jQuery constructor for the purpose of judging single tags, such as

Copy code The code is as follows:

// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,

然后把结果交给ret变量,基于ret的值又进行划分按照单标签和复杂标签分开处理ret值存在那就是匹配到了单标签然后再根据context是不是普通对象又分为两种情况isPlainObject是检测是不是普通对象的方法,如果是普通对象,就利用js原生方法createElement传入标签创建元素并放在一个数组里面,之所以这样是为了以后跟jquery对象合并方便,然后把数组赋值给selector,后采用对象冒充的方法调用attr方法,这里attr居然有3个参数,而平常我们使用的api里面是两个参数,其实jQuery中有很多类似的情况,同样的方法有着对内对外两个接口。第二个参数就是对象形式的上下文,因为attr可以像

复制代码 代码如下:

$("img").attr({ src: "test.jpg", alt: "Test Image" });

这给我们的其实就是我们以后可以$(‘

',{id:'div'})这样写了也是支持的。如果不是对象就直接创建元素不考虑属性。还是把创建的元素放在数组里面。如果ret没有值那就是复杂的标签了比如$(‘
231
')这样的这个时候原生的js就搞不定啦需要调取另外一个方法jQuery.buildFragment来处理,这个方法实现以后在学习吧,总之最后都会创建dom元素。最后返回合并后的结果

复制代码 代码如下:

return jQuery.merge( this, selector );

不像之前的return this这里是返回merge执行后的结果其实他的任务就是把放在数组里面的创建好的的dom元素合并到jquery元素中去,最终变成{0:div,length:1...}这样的对象形式。这样的话简标签情况就处理完毕。

然后else里面处理的是id的情况

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
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;
Copy after login

很简单直接调用原生js的id选择器但是有一些系统会出现bug

注释说的很清楚黑莓系统,就是元素已经不存在了但是依然能够匹配得到所以再加上父节点,不存在的元素肯定没有父节点的。还有一种情况就是ie和opera浏览器会出现按name值匹配的情况所以在做了一个判断

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

如果真的不幸出现了那就不能使用原生方法而是用find方法也就是使用sizzle引擎了,在大多数正常情况下就直接将获取到的元素放到this里面就可以啦然后修改下context的值。Ok终于把第一个大分支分析完了。然后再看根据match的第二个分支

 else if ( !context || context.jquery ) {
  return ( context || rootjQuery ).find( selector );
}
Copy after login

这里是如果没有上下文或者上下文是jquery对象的时候这个比较简单就是直接用find方法了rootjQuery 就是$(document)

最后字符串的情况上面都不属于的话

复制代码 代码如下:

return this.constructor( context ).find( selector );

This.constructor就是jQuery其实还是使用find方法。

以上所述就是本文的全部内容了,希望大家能够喜欢。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

Summary of commonly used file operation functions in PHP Summary of commonly used file operation functions in PHP Apr 03, 2024 pm 02:52 PM

目录1:basename()2:copy()3:dirname()4:disk_free_space()5:disk_total_space()6:file_exists()7:file_get_contents()8:file_put_contents()9:filesize()10:filetype()11:glob()12:is_dir()13:is_writable()14:mkdir()15:move_uploaded_file()16:parse_ini_file()17:

See all articles