代码之家  ›  专栏  ›  技术社区  ›  Mike

需要优化jQuery函数

  •  0
  • Mike  · 技术社区  · 17 年前

    1套:

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

    $(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

    $(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 回复  |  直到 9 年前
        1
  •  6
  •   Paolo Bergantino    17 年前

    $('.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