標籤:function input 首碼 val 隱式 精簡 css 賦值 one
1.將會重用的元素緩衝
//bad
var h = $(‘#hello‘).height();
$(‘#hello‘).css(‘height‘,h-20);
//good
var $hello = $(‘#hello‘),
h = $hello.height();
$hello.css(‘height‘,h-20);
2.盡量少設定全域變數,盡量在函數範圍內設定變數
3.在jQuery對象前加$首碼,便於識別
//bad
var hello = $(‘#hello‘),
value = hello.val();
//good
var $hello = $(‘#hello‘),
value = $hello.val();
4.將多條var語句合并成一條var語句,將未賦值的變數放到後面
//good
var $hello = $(‘#hello‘),
value = $hello.val(),
k = 3,
i,
j,
myArr = [];
5.統一使用on()方法
//bad
$hello.click(function(){
$hello.css(‘border‘,‘1px solid red‘);
$hello.css(‘color‘,‘blue‘);
});
$hello.hover(function(){
$hello.css(‘border‘,‘1px solid red‘);
});
//good
$hello.on(‘click‘,function(){
$hello.css(‘border‘,‘1px solid red‘);
$hello.css(‘color‘,‘blue‘);
});
$hello.on(‘hover‘,function(){
$hello.css(‘border‘,‘1px solid red‘);
});
6.精簡js
//bad
$hello.click(function(){
$hello.css(‘border‘,‘1px solid red‘);
$hello.css(‘color‘,‘blue‘);
});
//good
$hello.on(function(){
$hello.css({
‘border‘:‘1px solid red‘,
‘color‘:‘blue‘
});
});
7.鏈式操作
//bad
$hello.html(value);
$hello.on(‘click‘,function(){
alert(‘hello everyone‘);
});
$hello.fadeIn(‘slow‘);
$hello.animate({height:‘120px‘},500);
//good
$hello.html(value);
$hello.on(‘click‘,function(){
alert(‘hello everyone‘);
}).fadeIn(‘slow‘).animate({height:‘120px‘},500);
8.利用鎖進和換行提高代碼可讀性
//bad
$hello.html(value);
$hello.on(‘click‘,function(){
alert(‘hello everyone‘);
}).fadeIn(‘slow‘).animate({height:‘120px‘},500);
//good
$hello.html(value);
$hello
.on(‘click‘,function(){alert(‘hello everyone‘);})
.fadeIn(‘slow‘)
.animate({height:‘120px‘},500);
9.使用短路求值,短路求值是一個從左至右的運算式,用&&(邏輯與)或||(邏輯或)操作符
//bad
function init($myElement){
if(!$myElement){
$myElement = $(‘#myElement‘);
}
}
//good
function init($myElement){
$myElement = $myElement || $(‘#myElement‘);
}
10.選擇捷徑
//bad
if(myArr.length > 0){}
//good
if(myArr.length){}
11.緩衝父元素並在選擇子項目時重用這些已緩衝的父元素
//bad
var $container = $(‘#container‘),
$containerLi = $(‘#container li‘),
$containerLiSpan = $(‘#container li span‘);
//good
var $container = $(‘#container‘),
$containerLi = $(‘#container‘).find(‘li‘),
$containerLiSpan = $containerLi.find(‘span‘);
12.盡量少用通用選擇符(*)
13.避免隱式通用選擇符
//bad
$(‘.hello :radio‘)
//good
$(‘.hello input:radio‘)
14.最佳化選擇符
jQuery編程技巧