在学习jquery源码的时候,学到了其中的pushStack方法,在这里记录一下
源码为
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
}
比如在页面上有两个标签
<div>div</div>
<span>span</span>
这时,这么写
$("div").pushStack($("span"));
此时stack的结构为
由于stack的先入后出的原则,所以$("div").pushStack($("span")).css('background','red');显示为
而jquery的
这个方法可以追溯到上一层,如
jquery中的splice和选择器中的eq等,都使用的是这个原理