在學習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等,都使用的是這個原理