=================================================================
http://www.oschina.net/news/23240/jquery-skills?from=20111120
3. 数组方式使用jQuery对象运行选择器的结果是一个jQuery对象。然而,jQuery类库让你感觉你正在使用一个定义了index和长度的数组。
// Selecting all the navigation buttons:var buttons = $(‘#navigation a.button’);// We can loop though the collection:for(var i=0;i<buttons.length;i++){ console.log(buttons[i]); // A DOM element, not a jQuery object}// We can even slice it:var firstFour = buttons.slice(0,4);如果性能是你关注的,那么使用简单for或者while循环来处理,而不是$.each(),这样能使你的代码更快。
检查长度也是一个检查你的collection是否含有元素的方式。
if(buttons){ // This is always true // Do something}if(buttons.length){ // True only if buttons contains elements // Do something}9. $.proxy()使用callback方法的缺点之一是当执行类库中的方法后,context被设置到另外一个元素,例如:
<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(); });});你将遇到问题,button会消失,不是panel。使用$.proxy方法,你可以这样书写代码:
$(‘#panel’).fadeIn(function(){ // Using $.proxy to bind this: $(‘#panel button’).click($.proxy(function(){ // this points to #panel $(this).fadeOut(); },this));});这样才正确的执行。$.proxy方法接受两个参数,你最初的方法,还有context。这里阅读更多$.proxy in the docs.。
10. 判断页面是否太过复杂一个非常简单的道理,约复杂的页面,加载的速度越慢。你可以使用下面代码检查一下你的页面内容:
console.log( $(‘*’).length );以上代码返回的数值越小,网页加载速度越快。你可以考虑通过删除无用多余的元素来优化你的代码
11. 将你的代码转化成jQuery插件如果你要花一定得时间去开发一段jQuery代码,那么你可以考虑将代码变成插件。这将能够帮助你重用代码,并且能够有效的帮助你组织代码。创建一个插件代码如下:
(function($){ $.fn.yourPluginName = function(){ // Your code goes here return this; };})(jQuery);13. 在动画中使用delay()方法链式的动画效果是jQuery的强大之处。但是有一个忽略了的细节就是你可以在动画之间加上delays,如下:
// 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});jQuery动画帮了我们大忙,否则我们得自己处理一堆的细节,设置timtout,处理属性值,跟踪动画变化等等。
大家可以参考这个文章:jQuery animations