Home > Web Front-end > JS Tutorial > body text

Introduction to the use of end() and pushStack() in jQuery_jquery

WBOY
Release: 2016-05-16 17:56:36
Original
1076 people have browsed it

But when we write our own jQuery code, we rarely pay attention to or use pushStack(). If we need to write a plug-in involving DOM traversal, it will be especially useful.

Inside jQuery, pushStack The () method "tracks" the DOM result set returned by the previous method in the chain call by changing the prevObject property of a jQuery object (it is encapsulated by jQuery and is also a jQuery object. It is said to be "tracked" because what is actually stored is a Reference). When we call the end() method in a chain, the prevObject of the current jQuery object is returned internally. For more details, just look at the source code. Here is just a simple analysis, and here is an example:

html:

Copy code The code is as follows:


I am grandparent.

I am parent.

I am child .




javascript:
Copy code The code is as follows:

var els = $('#child').parent().parent();
console.dir( els);

Illustration:

After understanding this, we will make a grandparent plug-in to replace .parent().parent() for two consecutive calls. Use .grandparent() directly. If "accidentally" "If end() is not considered, the code is likely to look like this:

Copy the code The code is as follows:

$.fn.grandparent = function() {
return this.parent().parent();
};

Still using the above example :

Copy code The code is as follows:
$('#child').grandparent() .end(); //jQuery-[div#parent]


Obviously, in most cases this is not what we want, in fact we want to return directly through chained end() calls Go to jquery[div#child]. Now it’s time for pushStack to take action. We just need to add one line:

Copy code The code is as follows:

$.fn.grandparent = function() {
var els = this.parent().parent();
return this.pushStack( els.get());
};

Inside pushStack, encapsulate the DOM array returned by els.get() into a new jQuery object, and this(jQuery[div# child]) will be assigned to the prevObject of the newly constructed jQuery before, and finally return the new jQuery object.

So this time, when we use end() again:
Copy code The code is as follows:

var grandparent = $('#child').grandparent()./* jquery-[ div#grandparent]*/.end() /*jquery-[div#child]*/

The main idea of ​​this blog post comes from a blog in Learning JQuery. Thanks to the author for sharing. If you are interested, click jQuery pushStack.

Related labels:
end
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template