有時候你可能想要在元素上面儲存數(shù)據(jù)。由于瀏覽器兼容性問題,用原生javaScript處理元素上的數(shù)據(jù)可能會造成內(nèi)存溢出,jQuery可以幫你自動處理這些問題:
//儲存和取出元素數(shù)據(jù)$('#myDiv').data('keyName', {foo: 'bar'});$('#myDiv').data('keyName');	 //returns {foo: 'bar'}你可以在元素上面儲存任何數(shù)據(jù)。你甚至可以用Data方法把兩個元素連接起來。
比如說,你想要把li和li包含的div連接起來。
//用.data()把兩個元素連接起來$('#myList').each(function() {	var li = $(this);		//利用遍歷找到div.content,地址儲存在div變量處	var div = li.find('div.content');		//把div的內(nèi)容儲存在li中	li.data('contentDiv', div);});//無需再利用遍歷找到div.content//可以直接在li的數(shù)據(jù)上面調(diào)用var firstList = $('#myList li:first');firstList.data('contentDiv').html('new content!');jQuery在$命名空間提供了很多便捷的輔助方法,可以用來簡化日常操作。
比如,你可以用$.trim()來裁剪字符串兩段的空白:
//返回'hello, world'$.trim('  hello, world	');用$.each()遍歷數(shù)組,或者對象:
$.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()找到某個值在數(shù)組中的位置:
var myArray = ['a', 'b', 'c'];if ($.inArray(4, myArray) !== -1) {	console.log('found it');}$.inArray()如果找到了給定的值,返回該值在數(shù)組中的索引,否則返回-1。
用$.PRoxy()改變函數(shù)執(zhí)行的作用域
var myFunction = function() {	console.log(this);};var myObject = {	foo: 'bar'};myFunction();	//windowmyProxyFunction = $.proxy(myFunction, myObject);myProxyFunction();	//myObject$.proxy()接收第一個參數(shù)是函數(shù),第二個參數(shù)是指定一個對象,然后返回一個在指定對象作用域運行的函數(shù)。
這個例子中,myFuntion()因為是在全局作用域定義的,所以this是window;指定$.proxy()方法第二個參數(shù)myObject后,返回了在myObject對象作用域執(zhí)行的函數(shù),然后賦值給了myProxyFunction, 所以執(zhí)行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方法判斷數(shù)據(jù)類型令人十分困擾;例如數(shù)組元素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'新聞熱點
疑難解答