-9

我有一个如下数组

countries: [{
      "name": "Afghanistan",
      "cca2": "AF",
      "calling-code": "93"
    },
    //{"name":"Åland Islands","cca2":"AX","calling-code":"358"},
    {
      "name": "Albania",
      "cca2": "AL",
      "calling-code": "355"
    }, {
      "name": "Algeria",
      "cca2": "DZ",
      "calling-code": "213"
    }, {
      "name": "American Samoa",
      "cca2": "AS",
      "calling-code": "1684"
    }, {
      "name": "Andorra",
      "cca2": "AD",
      "calling-code": "376"
    }, {
      "name": "Angola",
      "cca2": "AO",
      "calling-code": "244"
    }, {
      "name": "Anguilla",
      "cca2": "AI",
      "calling-code": "1264"
    }, {
      "name": "Antigua and Barbuda",
      "cca2": "AG",
      "calling-code": "1268"
    }
     ]

我想遍历这个列表并创建如下选择列表

<select>
   <option value="AF">Afganisthan</option>
   ....
<select>

我做了这个

for (var i = 0; i < countries.length; i++) {
    out += "<option value='" + countries[i].cca2 + "'>" + countries[i].name + "</option>";
}

但什么都没有出现..

4

5 回答 5

0

试试这个 :

for(var i=0;i<countries.length;i++){
    $('select').append('<option value="'+countries[i].cca2+'">'+countries[i].name+'</option>');
}
于 2013-08-14T18:22:21.880 回答
0
<select id='mySelect'><select>

$.each(countries, function(i, e){
    $('#mySelect').append("<option value='" + e.cca2 +"'>" + e.name + "</option>");
})

Demo

于 2013-08-14T18:23:00.247 回答
0
    var obj = eval('{' + str + '}'); //where str is "countries: ..."
    $('<select>').appendTo(document.body);    
    for(var i = 0; i < obj.countries.length; i++)
    {
       $('<option>').val(obj.countries[i].cca2).text(obj.countries[i].name).appendTo('select');
    }
于 2013-08-14T18:23:47.780 回答
0
var out = '<select>';

countries.forEach(function(country) {
    out += '<option value=' + country.cca2 + '>' + country.name + '</option>';
});

out += '</select>';
于 2013-08-14T18:24:44.180 回答
0

试试下面的 javascript 代码片段

var countryJSON= eval('{'+countryString+'}');
$('<select>').appendTo("#yourForm");    
for(i=0;i<countryJSON['countries'].length;i++){    
 $('<option>').val(countryJSON.countries[i].cca2).text(countryJSON.countries[i].name).appendTo('select');
}
于 2013-08-14T18:38:11.513 回答