有没有更好的方法来编写我的jQuery代码

Is there any better way to write my jQuery Code?

本文关键字:我的 jQuery 代码 更好 方法 有没有      更新时间:2023-09-26

我编写了一些JavaScript来显示和巧妙地隐藏员工页面上的信息。本质上,有3个标志和3套描述。如果你将鼠标悬停在设计徽章上,它将显示设计团队的描述和图像,反之亦然。这是我的代码:

$('.emblem img:first').hover(
            function() {
                $('.description:eq(1), .description:eq(2)').css({opacity : 0.2});
                $('.devStaff').css({opacity : 0.2});
            },
            function(){
                $('.description:eq(1), .description:eq(2)').css({opacity : 1});
                $('.devStaff').css({opacity : 1});
            }
        );
        $('.emblem img:eq(1)').hover(
            function() {
                $('.description:eq(0), .description:eq(2)').css({opacity : 0.2});
                $('.designStaff').css({opacity : 0.2});
            },
            function(){
                $('.description:eq(0), .description:eq(2)').css({opacity : 1});
                $('.designStaff').css({opacity : 1});
            }
        );
        $('.emblem img:eq(2)').hover(
            function() {
                $('.description:eq(0), .description:eq(1)').css({opacity : 0.2});
                $('.designStaff').css({opacity : 0.2});
            },
            function(){
                $('.description:eq(0), .description:eq(1)').css({opacity : 1});
                $('.designStaff').css({opacity : 1});
            }
        );

现在看看这个,我觉得肯定有更好的方法可以做到这一点,我想知道是否有人能提供一些建议?

一般来说,你不应该重复自己(http://en.wikipedia.org/wiki/Don't_repeat_yourself),

试着调用一个更通用的函数,比如:

function fadeOut(eqNum1, eqNum2) {
    $('.description:eq('+eqNum1+'), .description:eq('+eqNum2+')').css({opacity : 0.2});
    $('.devStaff').css({opacity : 0.2});
}
 function fadeIn(eqNum1, eqNum2){
    $('.description:eq('+eqNum1+'), .description:eq('+eqNum2+')').css({opacity : 1});
    $('.devStaff').css({opacity : 1});
}
$('.emblem img:first').hover(fadeOut(1,2), fadeIn(1,2) );
$('.emblem img:eq(1)').hover(fadeOut(0,2),fadeIn(0,2));
$('.emblem img:eq(2)').hover(fadeOut(0,1),fadeIn(0,1));

您可以用:lt(3):替换:first:eq(1):eq(2)

    $('.emblem img:lt(3)').hover(
        function() {
            $('.description:lt(2)').css({opacity : 0.2});
            $('.designStaff').css({opacity : 0.2});
        },
        function(){
            $('.description:lt(2)').css({opacity : 1});
            $('.designStaff').css({opacity : 1});
        }
    );

我遵循我不久前加入书签的这些规则,我会挑衅地至少遵循第一条,至少使用#id而不是.class。

http://www.artzstudio.com/2009/04/jquery-performance-rules/