首页 > 代码库 > jQuery编程技巧
jQuery编程技巧
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 = http://www.mamicode.com/hello.val();
//good
var $hello = $(‘#hello‘),
value = http://www.mamicode.com/$hello.val();
4.将多条var语句合并成一条var语句,将未赋值的变量放到后面
//good
var $hello = $(‘#hello‘),
value = http://www.mamicode.com/$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编程技巧