jQuery学习之工具

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);
});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值