什么是jquery堆栈?

什么是jquery堆栈?,jquery,dom,Jquery,Dom,可能重复: 在jQueryAPI中,我看到了一个函数pushStack。描述如下:将DOM元素的集合添加到jQuery堆栈中。 有人知道jQuery堆栈是什么吗?它可以用来做什么?它与DOM有关系吗?当您将多个jQuery方法链接在一起,并且每个方法返回一个新的jQuery对象时,jQuery跟踪堆栈中的所有jQuery对象。这允许您返回到以前使用的jQuery对象,而无需将其保存在局部变量中。为了实现这一点,当jQuery方法作为方法调用的结果创建新的jQuery对象时,它会调用pushSt

可能重复:

在jQueryAPI中,我看到了一个函数
pushStack
。描述如下:
将DOM元素的集合添加到jQuery堆栈中。


有人知道jQuery堆栈是什么吗?它可以用来做什么?它与DOM有关系吗?

当您将多个jQuery方法链接在一起,并且每个方法返回一个新的jQuery对象时,jQuery跟踪堆栈中的所有jQuery对象。这允许您返回到以前使用的jQuery对象,而无需将其保存在局部变量中。为了实现这一点,当jQuery方法作为方法调用的结果创建新的jQuery对象时,它会调用
pushStack()
,以允许新对象参与堆栈

jQuery方法
.end()
在某种程度上与
.pushStack()
相反,因为它返回堆栈中的一项以获取先前的jQuery对象,并且可以多次调用它以继续返回堆栈。有关更多信息,请参阅

举一个使用
.pushStack()
的例子,假设您想要一个方法来获取容器中的所有文本节点,您可以这样做,并使用
.pushStack()
返回新的结果jQuery对象:


大多数jQuery的DOM遍历方法都在jQuery对象实例上操作,并生成一个新实例,以匹配不同的DOM元素集。发生这种情况时,就好像新的元素集被推到了对象内部维护的堆栈上。每个连续的过滤方法都会将一个新元素集推送到堆栈上。您可以使用不同的函数直接对此堆栈进行操作,例如:


查看jQuery源代码,堆栈引用jQuery对象实例中的当前元素集。把它想象成锁链。。过滤时,将添加到堆栈中。调用end()将弹出该集合并返回堆栈中的上一个集合
.pushStack()
允许您向该堆栈添加一组新元素

// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {

    // 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;

    if ( name === "find" ) {
        ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
    } else if ( name ) {
        ret.selector = this.selector + "." + name + "(" + selector + ")";
    }

    // Return the newly-formed element set
    return ret;
},
可以将其与.end()一起使用

见:

此外:

非常好的例子和现场讲解,非常感谢。
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {

    // 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;

    if ( name === "find" ) {
        ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
    } else if ( name ) {
        ret.selector = this.selector + "." + name + "(" + selector + ")";
    }

    // Return the newly-formed element set
    return ret;
},