[英]Better way to write a reptitive function?
我的代碼看起來像這樣:
$('.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');
});
有沒有更好的方法來編寫類似上面的內容,即使它有效?
您可以使用混合的公共類來對元素和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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.