2014-09-22 51 views
0

IM转述我的问题:下面的代码工作正常,每次仅一些jQuery的循环性能

$('.topCellNav_1').mouseover(function(){      
     $('.cell_1').not(this).fadeTo(50,0.4);     
}); 

$('.topCellNav_2').mouseover(function(){      
     $('.cell_2').not(this).fadeTo(50,0.4);     
}); 

$('.topCellNav_3').mouseover(function(){      
     $('.cell_3').not(this).fadeTo(50,0.4);     
}); 

$('.topCellNav_4').mouseover(function(){      
     $('.cell_4').not(this).fadeTo(50,0.4);     
}); 

$('.topCellNav_5').mouseover(function(){      
     $('.cell_5').not(this).fadeTo(50,0.4);     
}); 

等多达19个或更多块不同......

所以问题是---如何缩短上述使用循环

类似的东西代码:

var i=-1 
while (++i < 19) { 

$('.topCellNav_'+i).mouseover(function(){     
     $('.cell_'+i).not(this).fadeTo(50,0.4); 

}); 
} 

塔NKS

+0

另一种解决方案是像'topCellNav'添加一个普通类所有这些因素,然后'$( 'topCellNav')。鼠标悬停(函数(){ $('。cell_'+ this.className.match(/ topCellNav _(\ d +)/)[1])。not(this).fadeTo(50,0.4); #});' – 2014-09-22 08:49:39

+0

我编辑了问题 – VNicholson 2014-09-22 10:49:00

+0

您是否尝试过我建议的代码 – 2014-09-22 11:09:23

回答

0

您可以使用属性与选择开始

$('[class^="topCellNav_"').mouseover(function() { 
    var index = $(this).attr("class").split("_")[1]; 
    $('.cell_' + index).not(this).fadeTo(50, 0.4); 
}); 
+0

感谢您的回复......我检查了建议的答案,但是我不打印这些值!我需要循环的属性... – VNicholson 2014-09-22 09:59:07