jQuery核心之那些有效的方法
jQuery提供了一些很有效的方法,这些方法都在$命名空间之下,对常规的编码很有帮助,完整的api详见:utilities documentation on api.jquery.com
// Returns "lots of extra whitespace"
$.trim( " lots of extra whitespace " );
$.each() : 遍历数组和对象:
$.each([ "foo", "bar", "baz" ], function( idx, val ) {
console.log( "element " + idx + " is " + val );
});
$.each({ foo: "bar", baz: "bim" }, function( k, v ) {
console.log( k + " : " + v );
});
$.inArray():从数组中找出元素的索引下标,未找到则返回-1:
var myArray = [ 1, 2, 3, 5 ];
if ( $.inArray( 4, myArray ) !== -1 ) {
console.log( "found it!" );
}
$.extend():用后一个参数的属性来改变前一个参数的相对应的属性,返回改变后的对象。
var firstObject = { foo: "bar", a: "b" };
var secondObject = { foo: "baz" };
var newObject = $.extend( firstObject, secondObject );
console.log( firstObject.foo ); // "baz"
console.log( newObject.foo ); // "baz"
如果你不想改变前一个参数的对应属性,可以一个空对象来实现:
var firstObject = { foo: "bar", a: "b" };
var secondObject = { foo: "baz" };
var newObject = $.extend( {}, firstObject, secondObject );
console.log( firstObject.foo ); // "bar"
console.log( newObject.foo ); // "baz"
$.proxy():返回一个总是运行在给定的环境中的函数。
var myFunction = function() {
console.log( this );
};
var myObject = {
foo: "bar"
};
myFunction(); // window
var myProxyFunction = $.proxy( myFunction, myObject );
myProxyFunction(); // myObject
var myObject = {
myFn: function() {
console.log( this );
}
};
$( "#foo" ).click( myObject.myFn ); // HTMLElement #foo
$( "#foo" ).click( $.proxy( myObject, "myFn" ) ); // myObject