将变量值指定为变量名称
Assign variable value as variable name
问题是我想通过使用其他变量的值调用变量来缩短我的代码
长工作版本:
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
}
})
它将获得鼠标悬停的ID,然后使用开关检查它是否匹配其中一个变量
我想得到的是这样的东西:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
active_country_lift(this.id,this.id[0])
})
当然上面的代码不起作用,但是有解决方法吗?
更新:Arun的答案有效,很快就接受了它,至于要求完整代码的评论,这是我应用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)
}
}
它将用于世界地图,请随时提出任何建议以使其更具活力
您可以将国家/地区信息存储在对象(如键值对)中,然后使用括号表示法动态访问它
var countries = {
russia: new Array('-15px'),
switzerland: new Array('-5px')
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id][0])
})
如果您没有多个值,则
var countries = {
russia: '-15px',
switzerland: '-5px'
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id])
})
尝试使用eval()
函数
var russia = new Array('-15px')
var switzerland = new Array('-5px')
$('.country').mouseover(function(){
active_country_lift(this.id,eval(this.id)[0])
})
相关文章:
- 替换另一个变量对象中的变量值
- 如何将变量值附加到另一个变量
- html类名中的数字形式的Javascript变量值
- JavaScript - JSON 数据结构的构建 - 如何使用变量值更改键名
- 将变量值指定为变量名称
- GAS:在处理程序函数中使用变量时,如何更改全局变量值并保留其更改后的值
- jquery没有't从DIV数据id中获取PHP变量值,只输出变量名
- 将视图中的JavaScript变量值分配给控制器变量
- 如何将JavaScript变量值转换为PHP变量
- 如何从HTML元素或Javascript变量中设置idoc变量值
- console.log() 在变量值实际更改之前显示变量的更改值
- 如何在名称中使用其他变量值创建 javascript 变量
- JavaScript变量值是否可以存储在PHP变量中
- 使用变量名称字符串 - JavaScript 访问变量值
- 通过 Ajax 获取 PHP 变量值,变量名称作为参数
- 当更改复制变量的值时,它也在更改 AngularJS 中的主变量值
- Jquery/Javascript - 变量正在接受另一个变量值
- 获取 PHP 变量中的 JavaScript 变量值
- 在函数中使用变量值作为变量名
- 在网页刷新时增加变量的变量值