可能重複:
How does the jQuery pushStack function work?什麼是jQuery堆棧?
在jQuery的API,我看到一個功能pushStack
。描述是:Add a collection of DOM elements onto the jQuery stack.
有誰知道笏jQuery堆棧是什麼,它可以使用什麼?它與DOM有關係嗎?
可能重複:
How does the jQuery pushStack function work?什麼是jQuery堆棧?
在jQuery的API,我看到一個功能pushStack
。描述是:Add a collection of DOM elements onto the jQuery stack.
有誰知道笏jQuery堆棧是什麼,它可以使用什麼?它與DOM有關係嗎?
當您將多個jQuery方法鏈接在一起並且每個方法返回一個新的jQuery對象時,jQuery會跟蹤堆棧中的所有jQuery對象。這使您可以返回到以前使用的jQuery對象,而無需將其保存在局部變量中。爲了完成這個工作,當一個jQuery方法由於方法調用而創建一個新的jQuery對象時,它調用pushStack()
來允許新對象參與堆棧。
jQuery方法.end()
與.pushStack()
相反,它將堆棧中的一項返回到先前的jQuery對象,並且可以多次調用它以繼續返回堆棧。有關更多信息,請參閱the .end()
doc。
對於使用.pushStack()
的例子,假設你想將得到所有文本節點的容器的方法,你可以這樣做這樣並返回使用.pushStack()
新產生的jQuery對象:
jQuery.fn.textNodes = function() {
var nodes = [];
this.each(function() {
var node = this.firstChild;
while (node) {
if (node.nodeType == 3) {
nodes.push(node);
}
node = node.nextSibling;
}
});
return this.pushStack(nodes, "textNodes");
};
綜觀jQuery的源line 203 of core.js,堆棧指當前組元素在jQuery對象實例中。想想它就像鏈接..當你過濾你添加到堆棧。調用end()會彈出該設置並返回到堆棧中的前一個設置。 .pushStack()
允許您將一組新的元素添加到此堆棧。
神奇的例子,還有精準的解釋,非常感謝你。 – pilau 2013-07-10 12:35:32