需要优化jQuery函数

Mik*_*ike 0 optimization jquery

1套:

$('#tabs li:first-child').addClass('first-child');
$('.photos li:first-child').addClass('first-child');
$('#alphabet li:first-child').addClass('first-child');
Run Code Online (Sandbox Code Playgroud)

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)})});
Run Code Online (Sandbox Code Playgroud)

是否可以优化,减少代码?


感谢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)})});
Run Code Online (Sandbox Code Playgroud)

第二组(158-> 78):

$('#tabs, .photos, #alphabet').find('li:first-child').addClass('first-child');
Run Code Online (Sandbox Code Playgroud)

二手Dean Edwards包装工

Pao*_*ino 6

在处理元素集和CSS/Javascript时,通常的做法是给所有类似的类,如果可能的话,使它们更容易使用.然后你可以这样做:

$('.mysimilarclass li:first-child').addClass('first-child');
Run Code Online (Sandbox Code Playgroud)

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

$('#tabs, .photos, #alphabet').find('li:first-child').addClass('first-child');
Run Code Online (Sandbox Code Playgroud)

对于第二组,同样适用.您可以将它们全部"分组"为一个类,或者只汇总所需的所有选择器,然后只查找它们中的图像.另外,你可以利用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);
     });
});
Run Code Online (Sandbox Code Playgroud)

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