开发者

jQuery optimize code of multiple hover

Here's my code:

$('.tab_开发者_StackOverflow社区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.


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

for (var i = 1; i <= 8; i++) {
  var helper = function (sel, id) {
    $(sel).hover(function() {
      $(id).find('a').stop().toggleClass('hover', 500);
      return false;
    });
  };

  helper('.tab_map' + i + ' area', '#nav' + i);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜