高效jQuery
2014-02-25 18:21
435 查看
1.缓存变量
DOM遍历是昂贵的,所以尽量将会重用的元素缓存。
在新版jQuery中,更短的 on(“click”) 用来取代类似 click() 这样的函数。在之前的版本中 on() 就是 bind()。自从jQuery 1.7版本后,on() 附加事件处理程序的首选方法。然而,出于一致性考虑,你可以简单的全部使用 on()方法。
jQuery实现方法的链式操作是非常容易的。下面利用这一点。
你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。
将通用选择符放到后代选择符中,性能非常糟糕。
通用选择符有时是隐式的,不容易发现。
DOM遍历是昂贵的,所以尽量将会重用的元素缓存。
// 糟糕 h = $('#element').height(); $('#element').css('height',h-20); // 建议 $element = $('#element'); h = $element.height(); $element.css('height',h-20); 2.使用’On’
在新版jQuery中,更短的 on(“click”) 用来取代类似 click() 这样的函数。在之前的版本中 on() 就是 bind()。自从jQuery 1.7版本后,on() 附加事件处理程序的首选方法。然而,出于一致性考虑,你可以简单的全部使用 on()方法。
// 糟糕 $first.click(function(){ $first.css('border','1px solid red'); $first.css('color','blue'); }); $first.hover(function(){ $first.css('border','1px solid red'); }) // 建议 $first.on('click',function(){ $first.css('border','1px solid red'); $first.css('color','blue'); }) $first.on('hover',function(){ $first.css('border','1px solid red'); }) 3.链式操作[/code]
jQuery实现方法的链式操作是非常容易的。下面利用这一点。
// 糟糕 $second.html(value); $second.on('click',function(){ alert('hello everybody'); }); $second.fadeIn('slow'); $second.animate({height:'120px'},500); // 建议 $second.html(value); $second.on('click',function(){ alert('hello everybody'); }).fadeIn('slow').animate({height:'120px'},500); 4.熟记技巧[/code]
你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。
// 糟糕 $('#id').data(key,value); // 建议 (高效) $.data('#id',key,value); 5.避免通用选择符[/code]
将通用选择符放到后代选择符中,性能非常糟糕。
// 糟糕 $('.container > *'); // 建议 $('.container').children(); 6.避免隐式通用选择符[/code]
通用选择符有时是隐式的,不容易发现。
// 糟糕 $('.someclass :radio'); // 建议 $('.someclass input:radio');
相关文章推荐
- 解决jquery mobile的header和footer在点击屏幕的时候消失的办法
- jQuery Mobile 表单基础
- jquery 相册展示,带点击,带小图展示
- jQuery学习笔记—— .html(),.text()和.val()的使用和区别
- AJAX_jQuery框架,三种无刷新方法
- 用jQuery获取table中行id和td值
- jQuery 的 live() 方法对 hover 事件的处理
- jQuery 的 live() 方法对 hover 事件的处理
- jQuery 的 live() 方法对 hover 事件的处理
- jQuery 的 live() 方法对 hover 事件的处理
- jQuery中$.get、$.post、$.getJSON、$.ajax 方法详解
- liferay中使用jQuery Validation Engine进行ajax验证,不通过也提交表单的解决方案
- jquery.tmpl.js模板
- jQuery名字
- jQuery Mobile 列表内容
- 验证控件jquery.validate.js使用说明+中文API
- jQuery常用方法(二)-事件
- 导入jquery在线库和离线库
- jQuery学习--Chapter01小结(jQuery介绍)
- jQuery之四(事件与动画)