2011-10-15 127 views
0

我試圖創建一個for()循環與已被解碼的JSON數據,問題是將我的循環變量(在這種情況下爲i)添加到我引用的元素的末尾。對JSON對象/數組元素使用for循環?

例如,我的JSON結構,傾倒:

{ 
    "url": "http://www.example.com", 
    "rid": 1, 
    "rname": "Apple iPhone 4 Rotation", 
    "rmin": 90, 
    "rmax": 150, 
    "blank": 0, 
    "geo_country_0": "GB", 
    "geo_url_0": "http://en", 
    "geo_country_1": "FR", 
    "geo_url_1": "http://fr", 
    "geo_country_2": "ES", 
    "geo_url_2": "http://es" 
} 

geo_country_的情況下和與geo_url_我需要附加的數,在這種情況下,循環變量。

我的for循環的實際,爲了更好的理解:

for(i = 1; i < count; i++) { 
       $('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data.geo_url_i+ '"/></div>'); 
       $('select[name="g_country['+i+']"').find('option[value="' + data.geo_country_i+ '"]').attr('selected','selected'); 
      } 

到目前爲止,我已經試過:

  • 罩住的i[i]
  • 轉義爲\i。 (這可能是一個愚蠢的想法)。
  • 添加預定義+ like,+ data.geo_country + i +

我需要做些什麼才能讓i正確解釋?

任何幫助將不勝感激!

+0

您是否在嘗試引用像'data ['geo_country _'+ i]''data.geo_country_?'? – dgilland

回答

2

在JavaScript中,你可以用兩種方式解決的一個對象的屬性:

var value = myobject.myproperty; 
var value2 = myobject['myproperty']; 

使用這方面的知識,你可以重寫你的代碼如下:

 for(i = 1; i < count; i++) { 
      $('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data['geo_url_' + i] + '"/></div>'); 
      $('select[name="g_country['+i+']"').find('option[value="' + data['geo_country_' + i] + '"]').attr('selected','selected'); 
     } 
+0

道具,編輯和解釋。我會接受當計時器下降:)! – Avicinnian

1

訪問它像

data['geo_country_' + i] 

而且你應該沒有問題