简体   繁体   中英

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. 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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