读jQuery官方文档:数据方法与辅助方法
2015-09-30 18:30
826 查看
数据方法
有时候你可能想要在元素上面储存数据。由于浏览器兼容性问题,用原生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'
相关文章推荐
- 使用jquery-form.js,直接提交表单至后台(springmvc)
- jquery 实现可编辑的表格
- 深入Jquery-$.ajax 、$.get、$.post、$.getJSON
- Jquery插件easyUi表单验证提交
- Jquery on()方法 替代live(),bind()绑定事件
- 6、第六课,js jquery20150928
- jQuery插件之ajaxFileUpload
- jquery中live()与click()方法的区别
- jquery操作复选框(checkbox)的12个小技巧总结
- jquery 重复事件
- DOM对象和jQuery对象之间的相互转换
- jQuery基础---链式调用
- jQuery学习笔记三
- jQuery学习笔记二
- 编写更好的jQuery代码
- 网页语法高亮jquery插件SyntaxHighlighter使用教程
- Jquery学习应用之 zTree
- 基于jQuery Bar Indicator 插件实现进度条展示效果
- 新jQuery中attr 与 prop的不同
- jQuery的UI库的下载