// 糟糕
$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'
});
});
链式操作
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);
维持代码的可读性
伴随着精简代码和使用链式的同时,可能带来代码的难以阅读。添加缩紧和换行能起到很好的效果。
// 糟糕
$second.html(value);
$second.on('click',function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);
// 建议
$second.html(value);
$second
.on('click',function(){ alert('hello everybody');})
.fadeIn('slow')
.animate({height:'120px'},500);
选择短路求值
短路求值是一个从左到右求值的表达式,用 &&(逻辑与)或 ||(逻辑或)操作符。
// 糟糕
function initVar($myVar) {
if(!$myVar) {
$myVar = $('#selector');
}
}
// 建议
function initVar($myVar) {
$myVar = $myVar || $('#selector');
}
选择捷径
精简代码的其中一种方式是利用编码捷径。
// 糟糕
if(collection.length > 0){..}
// 建议
if(collection.length){..}
繁重的操作中分离元素
如果你打算对DOM元素做大量操作(连续设置多个属性或css样式),建议首先分离元素然后在添加。
// 糟糕
var
$container = $("#container"),
$containerLi = $("#container li"),
$element = null;
$element = $containerLi.first();
//... 许多复杂的操作
// better
var
$container = $("#container"),
$containerLi = $container.find("li"),
$element = null;
$element = $containerLi.first().detach();
//... 许多复杂的操作
$container.append($element);
熟记技巧
你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。
// 糟糕
$('#id').data(key,value);










