深入学习jquery源码之first()与eq()和end()
eq(index|-index)
概述
获取第N个元素
参数
index Integer
一个整数,指示元素基于0的位置,这个元素的位置是从0算起。
index Integer
一个整数,指示元素的位置,从集合中的最后一个元素开始倒数。(1算起)
获取匹配的第二个元素
This is just a test.
So is this
$("p").eq(1)
[ So is this
]
获取匹配的第二个元素
This is just a test.
So is this
$("p").eq(-2)
[ This is just a test.
]
first()
概述
获取第一个元素
获取匹配的第一个元素
- list item 1
- list item 2
- list item 3
- list item 4
- list item 5
$('li').first()
[ list item 1 ]
last()
概述
获取最后个元素
获取匹配的最后个元素
- list item 1
- list item 2
- list item 3
- list item 4
- list item 5
$('li').last()
[ list item 5 ]
end()
概述
回到最近的一个"破坏性"操作之前。即,将匹配的元素列表变为前一次的状态。
如果之前没有破坏性操作,则返回一个空集。所谓的"破坏性"就是指任何改变所匹配的jQuery元素的操作。这包括在 Traversing 中任何返回一个jQuery对象的函数--'add', 'andSelf', 'children', 'filter', 'find', 'map', 'next', 'nextAll', 'not', 'parent', 'parents', 'prev', 'prevAll', 'siblings' and 'slice'--再加上 Manipulation 中的 'clone'。
选取所有的p元素,查找并选取span子元素,然后再回过来选取p元素
Hello,how are you?
$("p").find("span").end()
[ Hello how are you?
]
jquery源码
首先了解下栈:栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。栈的规则是先进后出。下面看下jQuery中链式方法的使用:
$('ul').children('li').css("backgroundColor","#CCC");
首先选择页面中ul元素,再寻找其子元素中li,为其设置背景颜色为灰色。这里,ul首先入栈,子元素li后入栈,则css()最后操作的是li元素不是ul,这里是因为jQuery里所有链式操作都调用了jQuery中的工具方法——pushStack()。
首先新建一个ret对象,其中连接(merge)了jQuery和传入新对象(集合),然后设置ret对象的上级元素为this,返回ret。
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
// 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;
},
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]] : []);
},
end: function () {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
end()利用了pushStack中的prevObject,返回该对象,若该对象为空,返回构造函数。