jQuery使用技巧简单汇总


Posted in Javascript onApril 18, 2013

1.使用最新的jquery版本
觉得这个建议有待商榷,虽然越新的jquery版本性能上更加优秀,但是有些方法的变迁还是会导致一些bug,比如从1.4.2到1.5时很多朋友就抱怨ajax上出现问题了。建议是旧的页面的jquery升级需谨慎,新项目可以大胆的使用jquery新版本。

还有个建议是使用google的cdn上的jquery文件,加载速度更快。猛击Google Libraries API 进入查看。

<!-- Include a specific version of jQuery --> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
<!-- Include the latest version in the 1.6 branch --> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

2.保持选择器的简单
这个建议明河非常赞同,有很多朋友不喜欢给元素增加样式或id,希望保持html的简洁,使用jquery强大的选择器去检索元素,这不是好的习惯。首先越复杂的选择器,遍历的效率越低,这是显而易见的,最高效率无疑是使用原生的getElementById();其次,复杂的选择器将标签名称和层级结构固化在里面,假如你的html结构发生了改变,或标签发生了改变,都直接造成检索失败。
$('li[data-selected="true"] a') // Fancy, but slow 
$('li.selected a') // Better 
$('#elem') // Best

访问DOM,是javascript最耗资源和性能的部分,所以尽量避免复杂或重复的遍历DOM。
避免重复遍历DOM的方法就是将$()检索的元素存储到变量,比如下面的代码:
var buttons = $('#navigation a.button');

// 使用$前缀来标示jquery对象,是非常好的习惯,推荐使用。
var $buttons = $('#navigation a.button'); 
var $buttons = $('#navigation a.button');

jquery选择器支持大部分的css3伪类方法,像:visible, :hidden, :animated,虽然很便利,但请慎用,因为当你使用伪类选择器的时候,jQuery不得不使用querySelectorAll(),性能的损耗更大。

3.jQuery对象作为数组处理
jQuery对象定义了length属性,当使用数组的形式操作时候返回其实是DOM元素而不是子jQuery对象,比如下面代码。

// Selecting all the navigation buttons: 
var buttons = $('#navigation a.button');

// 遍历buttons对象
for(var i=0;i<buttons.length;i++){ 
console.log(buttons[i]); // 是DOM元素,而不是jQuery对象! 
}

// We can even slice it:
var firstFour = buttons.slice(0,4);

根据实验,使用for或while循环,执行效率比$.each()来的高。详细测试可以看several times faster。
使用length属性来检查元素存在性:
if(buttons){ // This is always true 
// Do something 
} if(buttons.length){ // True only if buttons contains elements 
// Do something 
}

4.selector属性
jQuery对象都带有一个selector属性,用于获取选择器名称,比如:
$('#container li:first-child').selector // #container li:first-child 
$('#container li').filter(':first-child').selector // #container li.filter(:first-child)

留意第二行代码,selector返回的是获取的元素完整的选择器。
这个属性常用于编写jquery插件的时候。

5.创建一个空的jQuery对象
这种情况应用场景不多,当你需要先创建个空的jQuery对象,然后使用add()方法向此对象注入jQuery对象时会用到。

var container = $([]); 
container.add(another_element);)

6.选择随机元素
应用场景不多,举个例子,现在你需要随机给li增加一个red的class。
需要扩展jquery的选择器,这段代码很好的演示了jQuery.expr的用法。
(function($){ 
var random = 0; $.expr[':'].random = function(a, i, m, r) { 
if (i == 0) { 
random = Math.floor(Math.random() * r.length); 
} 
return i == random; 
}; 
10. 
11.})(jQuery); 
12. 
13. 
14. 
15.$('li:random').addClass('glow');

7.使用css钩子
jQuery.cssHooks是1.4.3新增的方法,用的不估计不多,当你定义新的CSS Hooks时实际上定义的是getter和setter方法,举个例子,border-radius这个圆角属性想要成功应用于firefox、webkit等浏览器,需要增加属性前缀,比如-moz-border-radius和-webkit-border-radius。你可以通过定义CSS Hooks将其封装成统一的接口borderRadius,而不是一一设置css属性。
$.cssHooks['borderRadius'] = { 
get: function(elem, computed, extra){ 
// Depending on the browser, read the value of 
// -moz-border-radius, -webkit-border-radius or border-radius 
}, 
set: function(elem, value){ 
// Set the appropriate CSS3 property 
} 
}; 
10. 
11.// Use it without worrying which property the browser actually understands: 
12.$('#rect').css('borderRadius',5);

8.使用自定义的Easing(缓动动画效果)函数
easing plugin是用的非常多的函数,可以实现不少华丽的效果。当内置的缓动效果无法满足你的需求时,还可以自定义缓动函数。
$.easing.easeInOutQuad = function (x, t, b, c, d) { 
if ((t/=d/2) < 1) return c/2*t*t + b; 
return -c/2 * ((--t)*(t-2) - 1) + b; 
}; // To use it: 
$('#elem').animate({width:200},'slow','easeInOutQuad');

9.$.proxy()的使用
关于$.proxy(),明河曾经详细介绍过,传送门在此《jquery1.4教程三:新增方法教程(3)》。
jquery有个让人头疼的地方,回调函数过多,上下文this总是在变化着,有时候我们需要控制this的指向,这时候就需要$.proxy()方法。
<div id="panel" style="display:none"> 
<button>Close</button> 
</div> 
$('#panel').fadeIn(function(){ 
// this points to #panel 
$('#panel button').click(function(){ 
// this points to the button 
$(this).fadeOut(); 
}); 
10.});

嵌套的二个回调函数this指向是不同的!现在我们希望this的指向是#panel的元素。代码如下:
$('#panel').fadeIn(function(){ 
// Using $.proxy to bind this: $('#panel button').click($.proxy(function(){ 
// this points to #panel 
$(this).fadeOut(); 
},this)); 
});

10.快速获取节点数
这是个常用的技巧,代码如下:
console.log( $('*').length );

11.构建个jquery插件
(function($){ 
$.fn.yourPluginName = function(){ 
// Your code goes here 
return this; 
}; 
})(jQuery);

关于jquery插件的构建,明河曾发过系列教程,传送门:制作jquery文字提示插件—jquery插件实战教程(1)。
这里就不再详述。

12.设置ajax全局事件
关于ajax全局事件,明河曾发过完整的介绍文章,传送门:《jquery的ajax全局事件详解—明河谈jquery》。

13.延迟动画

// This is wrong: 
$('#elem').animate({width:200},function(){ 
setTimeout(function(){ 
$('#elem').animate({marginTop:100}); 
},2000); 
}); // Do it like this: 
$('#elem').animate({width:200}).delay(2000).animate({marginTop:100});

当存在多个animate动画时,如何处理动画的执行顺序是个烦心事,原文作者是建议使用delay()函数,如上面的代码,但明河的建议是使用queue()方法,因为delay你要考虑延迟多少时间,而queue没有这个问题,进入队列的函数会一个个顺序执行。可以看明河以前的文章queue和dequeue—明河谈jquery。

15.jquery的本地存储
本地存储在现在web应用中使用越来越频繁,jquery有个专门用于本地存储的插件叫$.jStorage jQuery plugin。

// Check if "key" exists in the storage 
var value = $.jStorage.get("key"); 
if(!value){ 
// if not - load the data from the server 
value = load_data_from_server(); 
// and save it 
$.jStorage.set("key",value); 
}
Javascript 相关文章推荐
jquery select(列表)的操作(取值/赋值)
Aug 06 Javascript
基于prototype扩展的JavaScript常用函数库
Nov 30 Javascript
jquery插件NProgress.js制作网页加载进度条
Jun 05 Javascript
jquery中的常见问题及快速解决方法小结
Jun 14 Javascript
js实现目录链接,内容跟着目录滚动显示的简单实例
Oct 15 Javascript
npm国内镜像 安装失败的几种解决方案
Jun 04 Javascript
详解微信小程序Radio选中样式切换
Jul 06 Javascript
深入浅出webpack教程系列_安装与基本打包用法和命令参数详解
Sep 10 Javascript
安装vue-cli的简易过程
May 22 Javascript
jQuery.validate.js表单验证插件的使用代码详解
Oct 22 jQuery
Echart折线图手柄触发事件示例详解
Dec 16 Javascript
基于vue实现web端超大数据量表格的卡顿解决
Apr 02 Javascript
document.documentElement的一些使用技巧
Apr 18 #Javascript
JQuery 图片的展开和伸缩实例讲解
Apr 18 #Javascript
jQuery基本选择器选择元素使用介绍
Apr 18 #Javascript
jQuery层次选择器选择元素使用介绍
Apr 18 #Javascript
jQuery基本过滤选择器使用介绍
Apr 18 #Javascript
使用jQuery内容过滤选择器选择元素实例讲解
Apr 18 #Javascript
jQuery随机切换图片的小例子
Apr 18 #Javascript
You might like
PHP 解决utf-8和gb2312编码转换问题
2010/03/18 PHP
thinkphp验证码显示不出来的解决方法
2014/03/29 PHP
php使用正则表达式去掉html中的注释方法
2016/11/03 PHP
php使用正则表达式获取字符串中的URL
2016/12/29 PHP
Laravel统计一段时间间隔的数据方法
2019/10/09 PHP
javascript控制swfObject应用介绍
2012/11/29 Javascript
javascript中打印当前的时间实现思路及代码
2013/12/18 Javascript
JavaScript中的console.profile()函数详细介绍
2014/12/29 Javascript
jQuery带时间的日期控件代码分享
2015/08/26 Javascript
JavaScript的React Web库的理念剖析及基础上手指南
2016/05/10 Javascript
Bootstrap Paginator分页插件使用方法详解
2016/05/30 Javascript
BootStrap selectpicker
2016/06/20 Javascript
jQuery Ajax 上传文件处理方式介绍(推荐)
2016/06/30 Javascript
轻松实现js选项卡切换效果
2016/09/24 Javascript
Vue数据驱动模拟实现1
2017/01/11 Javascript
解决Jstree 选中父节点时被禁用的子节点也会选中的问题
2017/12/27 Javascript
mongodb初始化并使用node.js实现mongodb操作封装方法
2019/04/02 Javascript
vue如何实现自定义底部菜单栏
2019/07/01 Javascript
vue设置一开始进入的页面教程
2019/10/28 Javascript
Python语言技巧之三元运算符使用介绍
2013/03/04 Python
详细讲解用Python发送SMTP邮件的教程
2015/04/29 Python
深入讲解Python编程中的字符串
2015/10/14 Python
在Python web中实现验证码图片代码分享
2017/11/09 Python
Python日期时间模块datetime详解与Python 日期时间的比较,计算实例代码
2018/09/14 Python
win10安装tensorflow-gpu1.8.0详细完整步骤
2020/01/20 Python
Python实现删除某列中含有空值的行的示例代码
2020/07/20 Python
谈谈python垃圾回收机制
2020/09/27 Python
浅析Python 中的 WSGI 接口和 WSGI 服务的运行
2020/12/09 Python
美国CVS药店官网:CVS Pharmacy
2018/07/26 全球购物
UNIONBAY官网:美国青少年服装品牌
2019/03/26 全球购物
Jar包的作用是什么
2014/03/30 面试题
办理信用卡工作证明
2014/01/11 职场文书
运动会入场词50字
2014/02/20 职场文书
青奥会口号
2014/06/12 职场文书
2019新员工试用期转正工作总结范文
2019/08/21 职场文书
《自然之道》读后感3篇
2019/12/17 职场文书