【发布时间】:2016-08-15 12:35:32
【问题描述】:
问题是我想通过使用其他变量的值调用变量来缩短我的代码
长期工作版本:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
switch(this.id){
case 'russia':
active_country_lift(this.id,russia[0])
break
case 'switzerland':
active_country_lift(this.id,switzerland[0])
break
}
})
它会得到 mouseovered 的 id 然后使用 switch 检查它是否匹配变量之一
我想要得到的是这样的:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
active_country_lift(this.id,this.id[0])
})
当然上面的代码是行不通的,但是有解决办法吗?
更新:Arun 的回答奏效了,很快我就会接受它,至于要求完整代码的 cmets,这是我应用 Arun 后的一部分
var countries = {
russia: ['-15px'],
switzerland: ['-5px']
}
$('.country_inactive').mouseover(function(){
active_country_lift(this.id, countries[this.id][0])
})
function active_country_lift(country, country_top){
if(!$('#'+country+'_active').hasClass('active')){
$('#'+country+'_active').stop().fadeIn(100).animate({
'top' : country_top
}, 200)
$('#'+country).stop().fadeOut(100)
}
}
它将用于世界地图,请随时提出任何建议以使其更加动态
【问题讨论】:
-
专业提示:除非您声明数组的长度,否则切勿在 JS 中使用
new Array。只需使用[]初始化数组即可。 -
你能否添加你想要实现的完整代码,这可能只能使用 CSS 来实现。
标签: javascript jquery html arrays dynamic