您的位置:首页 > Web前端 > JQuery

jQuery中的pushStack

2016-01-24 22:27 585 查看
在学习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等,都使用的是这个原理
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: