发布在:使用 jQuery Core

实用方法

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 文档 以获取更深入的解释。