版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013275171/article/details/85316850
Utility Methods (功能方法)
jQuery 在 $ 命名空间中提供许多功能性的方法。完整文档:Utility Documentation
$.trim() 移除起始和结尾的空白
$.trim( " lots of extra whitespace " );
// 返回值为:"lots of extra whitespace",去掉了起始和结尾的空白字符
$.each() 迭代数组和对象集中的所有元素。.each() 方法能被选择集呼叫,用以迭代选择集中的元素(选择集中元素的迭代,是 .each() 方法,而不是 $.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
检测值的类型
有时候 typeof 操作符的返回值会难以理解或者不稳定,此时可以使用jQuery提供的其他功能方法,来确认值的类型
$.isArray([]); // true
$.isFunction(function() {}); // true
$.isNumeric(3.14); // true
$.type()
$.type( true ); // "boolean"
$.type( 3 ); // "number"
$.type( "test" ); // "string"
$.type( function() {} ); // "function"
$.type( new Boolean() ); // "boolean"
$.type( new Number(3) ); // "number"
$.type( new String('test') ); // "string"
$.type( new Function() ); // "function"
$.type( [] ); // "array"
$.type( null ); // "null"
$.type( /test/ ); // "regexp"
$.type( new Date() ); // "date"
深入了解:jQuery.type()