gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:34:00 25 4
gpt4 key购买 nike

我编写了一些 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));

关于javascript - 有没有更好的方法来编写我的 jQuery 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8823519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com