有没有更好的方法来编写我的jQuery代码
Is there any better way to write my jQuery Code?
我编写了一些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/
相关文章:
- 我的jQuery插件参数没有正确启动,遇到了问题
- 我的jquery代码不起作用.为什么?
- 我的jquery中出现NaN错误
- 我如何才能找到哪些网站使用我的jQuery插件
- 如何使用我的Jquery代码创建委托事件侦听器
- 为什么我的jQuery点击函数没有触发
- 我的jQuery加载请求是否被调用了两次
- 为什么我的Jquery.ajax调用会触发错误事件
- 如何触发我的 jquery 表单提交
- 为什么我的jQuery .每次迭代都无法使用每个项目的属性
- 为什么我的jQuery UI对话框不起作用
- 在我的 jquery 函数中得到一个错误
- 我的jQuery UI对话框没有'如果前面没有警告,则不会打开
- 我的jquery在本地工作,但当它'it’s上传到我的网站上,它只起部分作用
- 我的jquery日历没有正确对齐
- 与我的jquery弹出窗口和自动调整文本区域大小有冲突
- 关于我的jQuery脚本+与iDevices的兼容性的建议
- 我的jquery方法没有'不起作用
- 我的jquery代码在谷歌chrome控制台中工作,而不是在保存它之后
- 为什么当我快速移动鼠标时,我的jQuery会崩溃