我正在尝试用jQuery做一个简单的任务:我有一个单词列表,当它们悬停时,应该淡化其相应的图像。例如:
<a href="#" class="yellow">Yellow</a>
<a href="#" class="blue">Blue</a>
<a href="#" class="green">Green</a>
<img src="yellow.jpg" class="yellow">
<img src="blue.jpg" class="blue">
<img src="green.jpg" class="green">
我目前正在为每个链接/图像这样做:
$('a.yellow').hover(
function () {
$('img.yellow').fadeIn('fast');
},
function () {
$('img.yellow').fadeOut('fast');
});
上面的方法运行正常,但是我还在学习,我想有更好的方法可以做到这一点,而不是重复功能。
有人能在这里给我一些启示吗?如何改进此代码?
答案 0 :(得分:4)
<a href="#" class="yellow" data-type="color">Yellow</a>
<a href="#" class="blue" data-type="color">Blue</a>
<a href="#" class="green" data-type="color">Green</a>
jQuery代码
$('a[data-type=color]').hover(
function () {
$('img.'+$(this).attr("class")).fadeIn('fast');
},
function () {
$('img.'+$(this).attr("class")).fadeOut('fast');
});
});
我认为你应该尝试这个。我使用data-
作为自定义属性的前缀,因为它符合html5。如果您愿意,可以说data-something
。
通常你可能不需要使用数据颜色自定义属性,但是因为我认为要使它更通用,我使用了该属性。你也可以这样做:
<a href="#" class="yellow">Yellow</a>
<a href="#" class="blue">Blue</a>
<a href="#" class="green">Green</a>
然后
$('a').hover(
function () {
$('img.'+$(this).attr("class")).fadeIn('fast');
},
function () {
$('img.'+$(this).attr("class")).fadeOut('fast');
});
});
但是这样,您应该确保所有链接都是与图像相关的链接。
答案 1 :(得分:2)
<a href="#" id="yellow" class="colorLink">Yellow</a>
<a href="#" id="blue" class="colorLink">Blue</a>
<a href="#" id="green" class="colorLink">Green</a>
<img src="yellow.jpg" class="yellow">
<img src="blue.jpg" class="blue">
<img src="green.jpg" class="green">
$("a.colorLink").hover(
function(){
$("img."+this.id).fadeIn('fast');
},
function(){
$("img."+this.id).fadeOut('fast');
}
);
这为与图像对应的每个链接设置唯一ID。