您的位置:首页 > Web前端 > JQuery

高效jQuery

2014-02-25 18:21 435 查看
1.缓存变量

DOM遍历是昂贵的,所以尽量将会重用的元素缓存。

// 糟糕

h = $('#element').height();
$('#element').css('height',h-20);

// 建议

$element = $('#element');
h = $element.height();
$element.css('height',h-20);

2.使用’On’

在新版jQuery中,更短的 on(“click”) 用来取代类似 click() 这样的函数。在之前的版本中 on() 就是 bind()。自从jQuery 1.7版本后,on() 附加事件处理程序的首选方法。然而,出于一致性考虑,你可以简单的全部使用 on()方法。

// 糟糕

$first.click(function(){
$first.css('border','1px solid red');
$first.css('color','blue');
});

$first.hover(function(){
$first.css('border','1px solid red');
})

// 建议
$first.on('click',function(){
$first.css('border','1px solid red');
$first.css('color','blue');
})

$first.on('hover',function(){
$first.css('border','1px solid red');
})

3.
链式操作[/code]
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);

4.
熟记技巧[/code]
你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。

// 糟糕

$('#id').data(key,value);

// 建议 (高效)

$.data('#id',key,value);

5.
避免通用选择符[/code]
将通用选择符放到后代选择符中,性能非常糟糕。

// 糟糕

$('.container > *');

// 建议

$('.container').children();

6.
避免隐式通用选择符[/code]
通用选择符有时是隐式的,不容易发现。

// 糟糕

$('.someclass :radio');

// 建议

$('.someclass input:radio');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: