請記住 – jQuery只是JavaScript。不要覺得它有能力來補償你糟糕的代碼。css
each
方法。
01 |
// jQuery's each method source |
02 |
each: function ( object, callback, args ) { |
03 |
var name, i = 0, |
04 |
length = object.length, |
05 |
isObj = length === undefined || jQuery.isFunction(object); |
06 |
07 |
if ( args ) { |
08 |
if ( isObj ) { |
09 |
for ( name in object ) { |
10 |
if ( callback.apply( object[ name ], args ) === false ) { |
11 |
break ; |
12 |
} |
13 |
} |
14 |
} else { |
15 |
for ( ; i < length; ) { |
16 |
if ( callback.apply( object[ i++ ], args ) === false ) { |
17 |
break ; |
18 |
} |
19 |
} |
20 |
} |
21 |
22 |
// A special, fast, case for the most common use of each |
23 |
} else { |
24 |
if ( isObj ) { |
25 |
for ( name in object ) { |
26 |
if ( callback.call( object[ name ], name, object[ name ] ) === false ) { |
27 |
break ; |
28 |
} |
29 |
} |
30 |
} else { |
31 |
for ( var value = object[0]; |
32 |
i < length &amp;amp;amp;&amp;amp;amp; callback.call( value, i, value ) !== false ; value = object[++i] ) {} |
33 |
} |
34 |
} |
35 |
36 |
return object; |
37 |
} |
糟糕的代碼:html
1 |
someDivs.each( function () { |
2 |
$( '#anotherDiv' )[0].innerHTML += $( this ).text(); |
3 |
}); |
優化的代碼:數組
1 |
var someDivs = $( '#container' ).find( '.someDivs' ), |
2 |
contents = []; |
3 |
4 |
someDivs.each( function () { |
5 |
contents.push( this .innerHTML ); |
6 |
}); |
7 |
$( '#anotherDiv' ).html( contents.join( '' ) ); |
each
(for)方法,咱們惟一要執行任務的關鍵是增長一個新的到一個數組…而不是查詢DOM中,取代了元素兩次獲取innerHTML屬性等。