Javascript 编写重复函数的更好方法?

Javascript 编写重复函数的更好方法?,javascript,jquery,Javascript,Jquery,我有如下代码: $('.item-one').mouseover(function() { $('.img-one').addClass('fit-img'); }); $('.item-two').mouseenter(function() { $('.img-two').addClass('fit-img'); }); $('.item-three').mouseenter(function() { $('.img-three').addClass('fit-im

我有如下代码:

$('.item-one').mouseover(function() {
    $('.img-one').addClass('fit-img');
});

$('.item-two').mouseenter(function() {
    $('.img-two').addClass('fit-img');
});

$('.item-three').mouseenter(function() {
    $('.img-three').addClass('fit-img');
});

有没有更好的方法来写上面这样的东西,即使它可以工作

您可以混合使用常用类对元素进行分组,并使用
数据
属性与元素一起存储元数据。试试这个:

$('.item').mouseover(函数(){
var target=$(this.data('target');
$(target.addClass('fit-img');
});
.img{
显示:无;
宽度:30px;
高度:30px;
}
.img.fit-img{display:block;}
.img one{背景色:红色;}
.img两个{背景色:绿色;}
.img三{背景色:蓝色;}


for循环对这些东西不起作用吗?你能显示Item 1/2/three和Img 1/2/three的HTML吗?你混合了
mouseover
mouseenter
-这是故意的吗?你可以为所有转换添加一个公共类,然后基于公共类而不是Item 1-Item-three添加/删除该类第三项…HTML中可能包含多少元素?