jQuery学习之工具

来源:互联网 发布:邓亚萍 20亿 知乎 编辑:程序博客网 时间:2024/05/01 18:41

jQuery实用工具

1.检测用户代理
使用JavaScript的navigator提供浏览器信息不够精确,不可拓展,不准确
比如使用浏览器检测
if(isIE){element.attachEvent('onclick',someHandler);}else if(isFirefox || isSafari){element.addEventListener('click',someHandler);}else{throw new Error('event Handling not supported.');}

不如使用对象检测
if(element.attachEvent){element.attachEvent('onclick',someHandler);}else if(element.addEventListener){element.addEventListener('click',someHandler);}else{throw new Error('event Handling not supported.');}

JQuery提供一组标致$.browser
$('#testButton').click(function(event){  var select = $('#testSubject')[0];  select.add(new Option('Two and \u00BD','2.5'),$.browser.msie ? 2 : select.options[2]  );});


2.确定方框模型
基本上分为W3C标准的方框模型和IE浏览器的方框模型$.boxModel
W3C中width和height只是决定元素内容尺寸,不包括内边距和边框宽度

IE的则包括内边距和边框宽度


3.检测要用的正确浮动样式

$.styleFloat


使用jQuery和其他库

$.noConflict()
一旦执行,则jQuery功能只能使用jQuery调用,不能用$符号调用

操作JavaScript对象和集合


1.修正字符串

$.trim(value)消除前后空格


2.对属性和集合进行迭代
$.each(container,callback) container为数组或者对象
var anArray = ['one','two','three',4];var anObject = {one:1, two:2, three:3};$.each(anArray,function(n,value){document.write('['+n+']='+value);});$.each(anObject,function(n,value){document.write('['+n+']='+value);});

3.对数组进行筛选
$.grep(array,callback,invert)
var originalArray = ['01826','abcde','1','78701-0339'];var badZips = $.grep(  originalArray,  function(value) { return value.match(/^\d{5}(-\d{4})?$/) != null;   },   true);

invert为true,意味着过滤掉callback中的条件


4.对数组进行转化
$.map(array,callback)
var strings = ['1','2','3','4','S','6'];var values = $.map(strings,function(value){var result = new Number(value);return isNaN(result) ? null : result;});var values = ['this','that','other thing'];$.map(values,function(value){return value.split('');})

5.从JavaScript数组上找到更多的快乐
$.inArray(value,array)
返回第一次出现的下标,如果搜索不到,返回-1
$.makeArray(object)
处理NodeList对象最有用
var images = document.getElementByTagName('img');
images = $.makeArray(images)
$unique(array)

返回原始数组中的唯一的元素组成的数组


6.扩展对象

$.extend(target,source1,source2,...,sourceN)


动态加载脚本

$.getScript(url,callback)
$('#loadButton').click(function(){  $.getScript('new.stuff.js'//,function(){$('#inspectButton').click()}  );});$('#inspectButton').click(function(){  someFunction(someVariable);});


0 0
原创粉丝点击