需要优化jQuery函数

时间:2009-05-02 19:26:32

标签: jquery optimization

1套:

$('#tabs li:first-child').addClass('first-child');
$('.photos li:first-child').addClass('first-child');
$('#alphabet li:first-child').addClass('first-child');

2集:

$(function(){
    $("#header-thumbs img").fadeTo("fast",1);
    $("#header-thumbs img").hover(function(){
        $(this).fadeTo("fast",.7)},function(){
        $(this).fadeTo("fast",1)})});
$(function(){$(".catalog dt img").fadeTo("fast",1);
    $(".catalog dt img").hover(function(){
        $(this).fadeTo("fast",.7)},function(){
        $(this).fadeTo("fast",1)})});
$(function(){$(".photos li img").fadeTo("fast",1);
    $(".photos li img").hover(function(){
    $(this).fadeTo("fast",.7)},function(){
    $(this).fadeTo("fast",1)})});

是否可以针对更少的代码进行优化?


感谢Paolo Bergantino的帮助,结果是:

优化并打包第一组(540-> 171):

$(function(){$("#header-thumbs, .catalog dt, .photos li").find("img").fadeTo("fast",1).hover(function(){$(this).fadeTo("fast",.7)},function(){$(this).fadeTo("fast",1)})});

第二组(158-> 78):

$('#tabs, .photos, #alphabet').find('li:first-child').addClass('first-child');

已使用Dean Edwards打包器

1 个答案:

答案 0 :(得分:6)

通常的做法是处理元素集和CSS / Javascript,以便为它们提供类似的类,如果可能的话,可以使它们更容易使用。然后你可以这样做:

$('.mysimilarclass li:first-child').addClass('first-child');

如果这不是一个选项,您也可以将所有选择器聚合为一个:

$('#tabs, .photos, #alphabet').find('li:first-child').addClass('first-child');

对于第二组,同样适用。您可以将它们全部“分组”为一个类,或者只汇总所需的所有选择器,然后只查找它们中的图像。另外,你可以利用jQuery的链接来不多次查询DOM:

$(function(){
    $("#header-thumbs, .catalog dt, .photos li")
     .find("img")
     .fadeTo("fast", 1)
     .hover(function() {
         $(this).fadeTo("fast", .7);
     }, function() {
         $(this).fadeTo("fast", 1);
     });
});

此外,如果可能的话,最好始终在选择器中添加预期具有类的元素。因此,不是.photos li,而是ul.photos li或任何具有photos类的元素。当然,这并不总是可行的,但无论什么时候都是可取的。

相关问题