简体   繁体   English

编写reptitive函数的更好方法是什么?

[英]Better way to write a reptitive function?

I have code that looks like this: 我的代码看起来像这样:

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

Is there a better way to write something like the above even though it works? 有没有更好的方法来编写类似上面的内容,即使它有效?

You can use a mix of common classes to group elements and data attributes to store meta data with the element. 您可以使用混合的公共类来对元素和data属性进行分组,以便使用元素存储元数据。 Try this: 试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM