jquery-filter-version

jquery1.0 版本的 filter函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//筛选出元素
//1.2.6 如果是Function的话直接grep
//如果不是Function那么调用multiFilter
filter: function(t) {
return this.pushStack(
t.constructor == Array &&
jQuery.map(this,function(a){
for ( var i = 0; i < t.length; i++ )
if ( jQuery.filter(t[i],[a]).r.length )
return a;
}) ||

t.constructor == Boolean &&
( t ? this.get() : [] ) ||

t.constructor == Function &&
jQuery.grep( this, t ) ||
//如果是字符串那么直接调用静态方法filter
jQuery.filter(t,this).r, arguments );
},

我们再看下静态的filter方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
filter: function(t,r,not) {
// Figure out if we're doing regular, or inverse, filtering
var g = not !== false ? jQuery.grep :
function(a,f) {return jQuery.grep(a,f,true);};

while ( t && /^[a-z[({<*:.#]/i.test(t) ) {

var p = jQuery.parse;//调用parse规则数组

for ( var i = 0; i < p.length; i++ ) {
var re = new RegExp( "^" + p[i][0]

// Look for a string-like sequence
.replace( 'S', "([a-z*_-][a-z0-9_-]*)" )

// Look for something (optionally) enclosed with quotes
.replace( 'Q', " *'?\"?([^'\"]*?)'?\"? *" ), "i" );

var m = re.exec( t );

if ( m ) {
// Re-organize the match
if ( p[i][1] )//Match: [@value='test'], [@foo] p[i][1] 为1
m = ["", m[1], m[3], m[2], m[4]];

// Remove what we just matched
t = t.replace( re, "" );

break;
}
}

// :not() is a special case that can be optomized by
// keeping it out of the expression list
if ( m[1] == ":" && m[2] == "not" )
r = jQuery.filter(m[3],r,false).r;

// Otherwise, find the expression to execute
else {
var f = jQuery.expr[m[1]];//访问expr 表达式数组
if ( f.constructor != String )
f = jQuery.expr[m[1]][m[2]];

// Build a custom macro to enclose it
eval("f = function(a,i){" +
( m[1] == "@" ? "z=jQuery.attr(a,m[3]);" : "" ) +
"return " + f + "}");

// Execute it against the current filter
r = g( r, f );//调用grep函数
}
}

// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
}

其实要么就是根据filter筛选 ,要么就是调用grep函数

我们来看看grep函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
grep: function(elems, fn, inv) {
// If a string is passed in for the function, make a function
// for it (a handy shortcut)
if ( fn.constructor == String )
fn = new Function("a","i","return " + fn);

var result = [];

// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0; i < elems.length; i++ )
if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) )
result.push( elems[i] );

return result;
}

欢迎关注我的公众号:沉迷Spring
显示 Gitment 评论
0%