jquery的追溯

我们都很熟悉jquery中的end()方法就是回到上一级的节点指向如下图: 

 

我们会考虑为什么呢,原理是什么?我们接着看下边的例子也许能发现点什么: 

 

这里我们会发现其实$(".table").find(".cn-radio") 的属性“prevObject”指向的是 $(".table")。 说到这里我们就要说到我们jquery里栈和追溯源码了。

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;

}

 

end: function() {

    return this.prevObject || this.constructor(null);

}

我们会发现通过栈查找的节点都会有一个prevObject属性指向上一个节点的集合, 我们用例子证实一下是不是这样的: 

到这里我们是不是都明白了追溯的原理,我们来看一下都哪些方法查找的节点列表可以用追溯的方法

map: function( callback ) {

    return this.pushStack( jQuery.map(this, function( elem, i ) {

        return callback.call( elem, i, elem );

    }));

},

 

slice: function() {

    return this.pushStack( slice.apply( this, arguments ) );

},

 

first: function() {

    return this.eq( 0 );

},

 

last: function() {

    return this.eq( -1 );

},

 

eq: function( i ) {

    var len = this.length,

        j = +i + ( i < 0 ? len : 0 );

    return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );

},

猜你喜欢

转载自tongdandanrrr.iteye.com/blog/2116990