您的位置:首页 > Web前端 > JQuery

jQuery入门:实用方法(Utility Methods)

2015-09-01 15:06 609 查看
jQuery 在
$
命名空间提供了一些实用方法。这些方法为实现例行的程序编制任务提供帮助。要完整的参考jQuery的实用方法,请访问utilities documentation on api.jquery.com

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

$.trim()

清除前后空格:

// 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 );
});


方法
.each()
用在包装集中遍历包装集中包含的元素。
.each()
不是
$.each()
,只应用于遍历包装集中的元素。

$.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"


如果你不想更改任何你传给
$.extend()
的对象,传一个空对象做第一个参数。

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()

返回一个函数,这个函数始终保持特定的作用域——就是说,设置
this
的意义在传递的第二个参数的函数范围内:

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


测试类型(Testing Type)

有些时候
typeof
操作符有些混乱或者不一致,因此,jQuery提供了一些实用方法来帮助确定一个值的类型。

首先,你有一些方法来测试是否是一个特定类型的一个特定值。

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


此外,还有
$.type()
用于检测内部类来创建一个值。你会发现这个方法是替代
typeof
操作符的更好的选择。

$.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 docs

原文地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: