我正在尝试用jQuery做一个简单的任务:我有一个单词列表,当悬停时,应该fadeIn其相应的图像。例如:
<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');
});上面的方法运行良好,但我仍在学习,我想有一种更好的方法来实现,而不是重复函数。
有人能给我点光吗?我如何改进这段代码?
发布于 2010-04-13 05:06:51
<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。
通常情况下,您可能不需要使用data-color自定义属性,但由于我认为为了使其更通用,我使用了该属性。你也可以做这样的代码:
<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');
});
});但是这样,你应该确保所有的链接都是与图片相关的链接。
发布于 2010-04-13 05:08:47
<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。
https://stackoverflow.com/questions/2625399
复制相似问题