jQuery 学习笔记 Utility Methods

本文介绍jQuery一些通用的方法,这些方法都是以$为命名空间的

$.trim() 移除头部和尾部的空白字符

$.each() 迭代数组和对象

1 $.each(["foo","bar","baz"],function(index,value){
2             console.log("element " + index + " is " + value);
3         });

输出

element 0 is foo
element 1 is bar
element 2 is baz
1 $.each({foo:"bar",baz:"bim"},function(key,value){
2             console.log("key:" + key + " value:" + value);
3         });

输出

key:foo value:bar
key:baz value:bim
 
$.inArray() 返回数组中一个元素的索引,如果不存在该元素则返回-1
1 var myArray = [1,2,3,4,5];
2         if($.inArray(4,myArray) !== -1){
3             console.log("found it");
4         }

输出 found it

$.extend() 用第二个对象的属性来改变第一个对象的属性

1 var object1 = {foo:"bar",a:"b"};
2         var object2 = {foo:"baz"};
3 
4         var newObject = $.extend(true,object1, object2);
5 
6         console.log(object1.foo);
7         console.log(object2.foo);

输出

baz
baz
如果不想改变传递给extend函数object的属性,可以将第一个参数设为false或{}
1 var object1 = {foo:"bar",a:"b"};
2         var object2 = {foo:"baz"};
3 
4         var newObject = $.extend({},object1, object2);
5 
6         console.log(object1.foo);
7         console.log(object2.foo);

输出

bar
baz
 
$.proxy()具体的使用用一个例子来说明
 1 var myFunction = function() {
 2                 console.log( this );
 3             };
 4         var myObject = {
 5                 foo: "bar"
 6         };
 7  
 8         myFunction(); // window
 9  
10         var myProxyFunction = $.proxy( myFunction, myObject );
11  
12         myProxyFunction(); // myObject

 

posted @ 2013-12-01 13:07  菜菜小三  阅读(252)  评论(0编辑  收藏  举报