2017-01-16 42 views
3

我有代码看起来像这样:更好的方式来写一个reptitive功能?

$('.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'); 
}); 

有没有更好的方式来写一样的东西,即使它的工作原理上面?

+0

不要for循环为这些事情的工作? –

+0

你可以显示Item-one/two/three和Img-one/two/three的HTML吗? –

+0

你有'mouseover'和'mouseenter'的混合物 - 那是故意的吗? –

回答

4

您可以使用混合的通用类将元素和data属性分组以存储元素与元素。试试这个:

$('.item').mouseover(function() { 
 
    var target = $(this).data('target'); 
 
    $(target).addClass('fit-img'); 
 
});
.img { 
 
    display: none; 
 
    width: 30px; 
 
    height: 30px; 
 
} 
 
.img.fit-img { display: block; } 
 

 
.img-one { background-color: red; } 
 
.img-two { background-color: green; } 
 
.img-three { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" class="item" data-target=".img-one">one</a> 
 
<a href="#" class="item" data-target=".img-two">two</a> 
 
<a href="#" class="item" data-target=".img-three">three</a> 
 

 
<div class="img img-one"></div> 
 
<div class="img img-two"></div> 
 
<div class="img img-three"></div>

相关问题