我想知道是否可以使以下代码更简洁:
$('#americasTrigger').hover(
function () {
$('#americasImg').fadeIn()
},
function(){
$('#americasImg').fadeOut()
}
);
$('#europeTrigger').hover(
function () {
$('#europeImg').fadeIn();
},
function(){
$('#europeImg').fadeOut();
}
);
$('#middleEastTrigger').hover(
function () {
$('#middleEastImg').fadeIn();
},
function(){
$('#middleEastImg').fadeOut();
}
);
//More etc
每个国家/地区名称保持不变,并在末尾添加“Trigger”或“Img”。这里有很多重复,这表明我并没有采用最好的方法。
我有一些想法:
- 创建案例场景,或
- 以某种方式获取用于选择的选择器,使其成为字符串,拆分其名称以捕获正在使用的国家/地区,并将其应用到末尾带有“Img”的嵌套淡入/淡出函数。
这可能吗,还是我太花哨了?
编辑1:非常感谢您的所有回复,很抱歉没有发布 html,我已将其放在下面。 简而言之,我在(地球的)背景图像上使用图像映射作为悬停触发器来淡入/淡出我的绝对定位的悬停图像。
<div class="mapTub">
<img src="images/transparentPixel.png" class="mapCover" usemap="#worldMap" width="524px" height="273px"/>
<map name="worldMap" id="worldMap">
<area id="americasTrigger" shape="poly" coords="1,2,3" href="#americas" />
<area id="europeTrigger" shape="poly" coords="4,5,6" href="#europe" />
<area id="middleEastTrigger" shape="poly" coords="7,8,9" href="#middleEast" />
</map>
<img src="images/International_americas_dark.png" class="americas" id="americasImg" />
<img src="images/International_europe_dark.png" class="europe" id="europeImg" />
<img src="images/International_middleEast_dark.png" class="middleEast" id="middleEastImg" />
</div>
<小时/>
Reigel 的回答似乎是正确的选择,我会尝试一下并报告,欢迎进一步评论! :)
最佳答案
我,不了解 html,建议这个...
$('#americasTrigger, #europeTrigger, #middleEastTrigger').hover(
function () {
var id = this.id;
$('#'+id.replace('Trigger', 'Img')).fadeIn();
//$('#'+id.slice('0',id.indexOf('Trigger'))+'Img').fadeIn();
},
function(){
var id = this.id;
$('#'+id.replace('Trigger', 'Img')).fadeOut();
//$('#'+id.slice('0',id.indexOf('Trigger'))+'Img').fadeOut();
}
);
您还可以按照Anurag的建议使用.replace()
在下面的评论中...
id ='europeTrigger';
alert(id.slice('0',id.indexOf('Trigger'))); // alerts 'europe'
// '#'+id.slice('0',id.indexOf('Trigger'))+'Img' is '#europeImg'
demo
关于jquery - 多个选择器或多个函数 - 有效率提升吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3369085/