假设我有$(‘mySelector:first’);和$(‘mySelector’).first();.哪种方式是最有效率的?我看着源头,但还是无法想像出来.
看起来在第一种情况下,jQuery会遍历每个项目,直到得到第一个:
CHILD: function( elem,match ) {
var type = match[1],node = elem;
switch ( type ) {
...
case "first":
while ( (node = node.prevIoUsSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
...
}
}
在第二种情况下,jQuery切片集合,但我不知道它的效率如何:
function first() {
return this.eq( 0 );
};
function eq( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i,+i + 1 );
};
解决方法
当前接受的答案与
tests across many browsers比较不一致:first和:eq(0)到.first()和.eq(0).
对于当前主要的桌面浏览器:
$(‘foo’).first()比$(‘foo:first’)快四倍,
如果你想检查方法,here are the tests and their current results.