jQuery对象的入栈:实质就是返回一个新的jQuery对象,新的jQuery对象的prevObject属性保存着前一个(当前)jQuery对象。
var p = $('p');//选中三个空的p var p1 = $(); console.log(p); console.log(p1);

<script> window.onload = function(){ $('p').pushStack($('span')).css('background-color','red').prevObject.css('background-color','yellow'); } </script>
或者将prevObject替换为end():
end: function() { return this.prevObject || this.constructor(null); },
$('p').pushStack($('span')).css('background-color','red').end().css('background-color','yellow');
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; },
constructor: jQuery,this.constructor()创建一个空的jQuery对象,
工具方法merge():第二个参数必须要有数值属性。
merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; },
<script> window.onload = function(){ var test = document.getElementById('demo'); $('p').pushStack(test).css('background-color','red').end().css('background-color','yellow'); } </script>
这是因为test没有length属性,如果将test变成数组形式[test],就可以将span元素的背景显示红色
$('p').pushStack([test]).css('background-color','red').end().css('background-color','yellow');