高效的jQuery
选择捷径
// 糟糕 if(collection.length > 0){..} // 建议 if(collection.length){..}
熟记技巧
// 糟糕 $('#id').data(key,value); // 建议 $.data('#id',key,value);
精简javascript
// 糟糕 $first.click(function(){ $first.css('border','1px solid red'); $first.css('color','blue'); }); // 建议 $first.on('click',function(){ $first.css({ 'border':'1px solid red', 'color':'blue' }); });
避免多个id选择符
// 糟糕 $('#div #con'); // 建议 $('#con');
优化选择符
$('div#div'); $('div#div a.address'); // 建议 $('#div'); $('#div .address');
选择捷径
// 糟糕 d = $('#ele').height(); $('#ele').css('height',d-20); // 建议 $ele = $('#ele'); d = $ele.height(); $ele.css('height',d-20)
避免全局变量
// 糟糕 $ele = $('#ele'); d = $ele.height(); $ele.css('height',d-20); $('#ele').css('height',d-20); // 建议 var $ele = $('#ele'); var d = $ele.height(); $ele.css('height',d-20);
链式操作
// 糟糕 $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);