簡體   English   中英

將變量值分配為變量名稱

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

它將獲得mouseovered的ID,然后使用switch檢查它是否與變量之一匹配

我想要獲得的是這樣的:

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

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

當然,上面的代碼不起作用,但是有沒有解決方法?

更新:阿倫的答案行之有效,很快就無法接受,至於要求提供完整代碼的評論,這是我應用阿倫的答案之后的一部分

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM