更高效的使用JQuery 这里总结了8个小技巧
1、DOM遍历是昂贵的,将变量缓存起来。
//不推荐 varh=$('#ele').height(); $('#ele').css('height',h-20);
//推荐 var$ele=$('#ele'); varh=$ele.height(); $ele.css('height',h-20);
2、优化选择符。
//不推荐 $('div#myid')
//推荐 $('#myid')
3、避免隐式通用选择符。
//不推荐 $('.someclass:radio')
//推荐 $('.someclassinput:radio')
4、避免通用选择符。
//不推荐 $('.container>*')
//推荐 $('.container').children()
5、尽可能保持代码简洁。
//不推荐 if(arr.length>0){}
//推荐 if(arr.length){}
6、尽可能地合并函数。
//不推荐 $f.on("click",function(){ $(this).css('border','1pxsolidred'); $(this).css('color','blue'); });
//推荐 $f.on("click",function(){ $(this).css({ 'border':'1pxsolidred', 'color':'blue' }); });
7、尽可能使用链式操作。
//不推荐 $ele.html(); $ele.on("click",function(){}); $ele.fadeIn('slow');
//推荐 $ele.on("click",function(){ }).fadeIn('slow').animate({height:'12px'},500);
8、对DOM元素作大量操作,先分离在追加
//不推荐 var$container=$('#somecontainer'); var$ele=$container.first(); .......一系列复杂操作
//推荐 var$container=$('#somecontainer'); var$ele=$container.first().detach(); .......一系列复杂操作 $container.append($ele);