发布于:使用 jQuery 核心

实用工具方法

jQuery 在 $ 命名空间中提供了几种实用工具方法。这些方法有助于完成常规的编程任务。有关 jQuery 实用工具方法的完整参考,请访问 api.jquery.com 上的实用工具文档

下面是一些实用工具方法的示例

link $.trim()

移除开头和结尾的空白字符

1
2
// Returns "lots of extra whitespace"
$.trim( " lots of extra whitespace " );

link $.each()

迭代数组和对象

1
2
3
4
5
6
7
$.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 );
});

可以在选择器上调用 .each() 方法来迭代选择器中包含的元素。应该使用 .each() 而不是 $.each() 来迭代选择器中的元素。

link $.inArray()

返回一个值在数组中的索引,如果该值不在数组中则返回 -1

1
2
3
4
5
var myArray = [ 1, 2, 3, 5 ];
if ( $.inArray( 4, myArray ) !== -1 ) {
console.log( "found it!" );
}

link $.extend()

使用后续对象的属性更改第一个对象的属性

1
2
3
4
5
6
7
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"

如果你不想更改传递给 $.extend() 的任何对象,请传入一个空对象作为第一个参数

1
2
3
4
5
6
7
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"

link $.proxy()

返回一个始终在提供的作用域中运行的函数——即将传入函数内部的 this 设置为第二个参数。

1
2
3
4
5
6
7
8
9
10
11
12
var myFunction = function() {
console.log( this );
};
var myObject = {
foo: "bar"
};
myFunction(); // window
var myProxyFunction = $.proxy( myFunction, myObject );
myProxyFunction(); // myObject

如果你有一个包含方法的对象,你可以传入该对象和一个方法的名称来返回一个始终在该对象作用域中运行的函数。

1
2
3
4
5
6
7
8
var myObject = {
myFn: function() {
console.log( this );
}
};
$( "#foo" ).click( myObject.myFn ); // HTMLElement #foo
$( "#foo" ).click( $.proxy( myObject, "myFn" ) ); // myObject

link 测试类型

有时 typeof 运算符 可能会令人困惑或不一致,因此 jQuery 没有使用 typeof,而是提供了实用工具方法来帮助确定值的类型。

首先,你可以使用方法来测试特定值是否属于特定类型。

1
2
3
$.isArray([]); // true
$.isFunction(function() {}); // true
$.isNumeric(3.14); // true

此外,还有 $.type() 方法,用于检查用于创建值的内部类。你可以将此方法视为 typeof 运算符的更好替代品。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.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"

与往常一样,你可以查看 API 文档 以获取更深入的解释。