数据方法有时候你可能想要在元素上面储存数据。由于浏览器兼容性问题,用原生javaScript处理元素上的数据可能会造成内存溢出,jQuery可以帮你自动处理这些问题:
//储存和取出元素数据
$('#myDiv').data('keyName', {foo: 'bar'});
$('#myDiv').data('keyName'); //returns {foo: 'bar'}
你可以在元素上面储存任何数据。你甚至可以用Data方法把两个元素连接起来。
比如说,你想要把li和li包含的div连接起来。
//用.data()把两个元素连接起来
$('#myList').each(function() {
var li = $(this);
//利用遍历找到div.content,地址储存在div变量处
var div = li.find('div.content');
//把div的内容储存在li中
li.data('contentDiv', div);
});
//无需再利用遍历找到div.content
//可以直接在li的数据上面调用
var firstList = $('#myList li:first');
firstList.data('contentDiv').html('new content!');
辅助方法jQuery在$命名空间提供了很多便捷的辅助方法,可以用来简化日常操作。
比如,你可以用$.trim()来裁剪字符串两段的空白:
//返回'hello, world'
$.trim(' hello, world');
用$.each()遍历数组,或者对象:
$.each(['foo', 'bar', 'baz'], function(index, value) {
console.log('Index: ' + index + ' Value: ' + value);
});
$.each({foo: 'bar', baz: 'bim'}, function(k, v) {
console.log(k + ' : ' + v);
});
注意,$.each()和.each()是不一样的,.each()用于遍历jQuery对象。
还可以用$.inArray()找到某个值在数组中的位置:
var myArray = ['a', 'b', 'c'];
if ($.inArray(4, myArray) !== -1) {
console.log('found it');
}
$.inArray()如果找到了给定的值,返回该值在数组中的索引,否则返回-1。
用$.PRoxy()改变函数执行的作用域
var myFunction = function() {
console.log(this);
};
var myObject = {
foo: 'bar'
};
myFunction();//window
myProxyFunction = $.proxy(myFunction, myObject);
myProxyFunction();//myObject
$.proxy()接收第一个参数是函数,第二个参数是指定一个对象,然后返回一个在指定对象作用域运行的函数。
这个例子中,myFuntion()因为是在全局作用域定义的,所以this是window;指定$.proxy()方法第二个参数myObject后,返回了在myObject对象作用域执行的函数,然后赋值给了myProxyFunction, 所以执行myProxyFunction后,this返回myObjet。
有时候你有一个对象方法,你想要this总是指向该对象的时候:
var myObj = {
myFn: function() {
console.log(this);
}
}
$('#foo').click(myObj.myFn); //HTMLElement #foo,这不是我们想要的,我们想要this返回myObj
$('#foo').click($.proxy(myObj, 'myFn');//myObj
有时候,使用原生的typeof方法判断数据类型令人十分困扰;例如数组元素typeof返回的是object(因为array类型在Javascript中是也是对象);自定义的对象typeof全部返回object;虽然是正确的,但是如果我们想要更加精准的类型呢?
在jQuery中,你可以这样:
$.isArray([]);//true
$.isFunction(function() {});//true
$.isNumberic(3.14);//true
也可以这样:
$.type(true);//'boolean'
$.type(3);//'number'
$.type("text");//'string'
$.type(function() {});//'function'
$.type(new Boolean());//'boolean'
$.type(new Number(3));//'number'
$.type(new String('text'));//'string'
$.type(new Function());//'function'
$.type([]);//'array'
$.type(null);//'null'
$.type( /text/ ); //'regexp'
$.type(new Date()); //'date'