【问题标题】:Assign variable value as variable name将变量值分配为变量名
【发布时间】: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)
    }
}

它将用于世界地图,请随时提出任何建议以使其更加动态

【问题讨论】:

标签: javascript jquery html arrays dynamic


【解决方案1】:

您可以将国家/地区信息存储在键值对之类的对象中,然后使用bracket notation 动态访问它

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])
})

【讨论】:

  • new Array('-15px') ==> '-15px'。为什么要使用数组。
  • @Tushar 它实际上给了['-15px']
  • @Tushar 可能有多个值,不确定
  • 如果 russiaswitzerland 是全局变量,您甚至可以只使用 window[this.id] 而不是创建包装对象,但创建包装对象更好,因为全局变量是不好的做法。跨度>
  • @4castle 是的,你可以。但是使用对象而不是全局变量是更好的做法
【解决方案2】:

尝试使用eval()函数

var russia = new Array('-15px')
var switzerland = new Array('-5px')

$('.country').mouseover(function(){
   active_country_lift(this.id,eval(this.id)[0])     
})

【讨论】:

  • 大多数人将eval 发音为evil,因为它既邪恶又低效。这是一个有效的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多