jQuery优化多次hover代码
这是我的代码:
$('.tab_map1 area').hover(function(){
$('#nav1').find('a').stop().toggleClass('hover', 500);
return false;
});
$('.tab_map2 area').hover(function(){
$('#nav2').find('a').stop().toggleClass('hover', 500);
return false;
});
$('.tab_map3 area').hover(function(){
$('#nav3').find('a').stop().toggleClass('hover', 500);
return false;
});
$('.tab_map4 area').hover(function(){
$('#nav4').find('a').stop().toggleClass('hover', 500);
return false;
});
... (there's 8 of them)
我不想多次重复相同的代码,而是以某种方式对其进行优化。是否有机会用一些索引值替换 .tab_map1-8 和 #nav1-8 ?
我尝试过:
var n = 8;
$('li.tab_map area').eq(n).hover(function(){
$('#nav').eq(n).find('a').stop().toggleClass('hover', 500);
return false;
});
和:
$("#navibar ul").each(function(index) {
$('.tab_map:eq(' + index + ') area').hover(function(index){
$('#nav:eq(' + index + ')').find('a').stop().toggleClass('hover', 500);
return false;
});
});
两者都不起作用。
Here's my code:
$('.tab_map1 area').hover(function(){
$('#nav1').find('a').stop().toggleClass('hover', 500);
return false;
});
$('.tab_map2 area').hover(function(){
$('#nav2').find('a').stop().toggleClass('hover', 500);
return false;
});
$('.tab_map3 area').hover(function(){
$('#nav3').find('a').stop().toggleClass('hover', 500);
return false;
});
$('.tab_map4 area').hover(function(){
$('#nav4').find('a').stop().toggleClass('hover', 500);
return false;
});
... (there's 8 of them)
I'd like to not repeat the same code multiple times but optimize it somehow. Is there a chance to replace .tab_map1-8 and #nav1-8 with some index value?
I tried:
var n = 8;
$('li.tab_map area').eq(n).hover(function(){
$('#nav').eq(n).find('a').stop().toggleClass('hover', 500);
return false;
});
and:
$("#navibar ul").each(function(index) {
$('.tab_map:eq(' + index + ') area').hover(function(index){
$('#nav:eq(' + index + ')').find('a').stop().toggleClass('hover', 500);
return false;
});
});
Both doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是在 1-8 范围内使用
for
循环。然后为每个索引建立选择器。例如The easiest way to do this is to use a
for
loop over the range 1-8. Then build up the selector for each index. For example