在jquery中填充来自2维数组的下拉列表

时间:2015-10-28 08:52:40

标签: javascript jquery arrays

我有以下下拉选择:

var month = ['Jan','Feb','March'];
var newArr = ["single Val"];
var j =0;
for(var i=1; i<(month.length+4)-1; i++){
    if(i%2==0){
        newArr[i] = 'two numbers';
    }else{
         newArr[i] = month[j];
        j++;
    }
}
newArr.push("singleval");
alert(newArr);
console.log(newArr);

我需要使用此类型的Javascrippt数组中的值来填充它:

<select id="start" onchange="calcRoute();"></select>

我尝试了以下方法,但它不起作用。

{"name":"Hotel1","address":"Bondi Beach","lat":"6.369869","lng":"80.042055","thumb_path":"img\/hotel1.jpg"},{"name":"Hotel2","address":"Coogee Beach","lat":"6.025822","lng":"80.305727","thumb_path":"img\/hotel2.jpg"},{"name":"Hotel3","address":"Cronulla Beach","lat":"6.691994","lng":"79.928771","thumb_path":"img\/hotel3.jpg"},{"name":"Hotel4","address":"Manly Beach","lat":"6.887130","lng":"80.093420","thumb_path":"img\/hotel4.jpg"},{"name":"Hotel5","address":"Maroubra Beach","lat":"7.362609","lng":"79.825005","thumb_path":"img\/hotel5.jpg"}

请建议修复。

1 个答案:

答案 0 :(得分:2)

选择器$('#start select')将选择<select>元素中的#start元素,该元素不起作为select本身的{是start的ID。要正确选择元素,请使用

$('#start') // or $('select#start')

最好不要乱用HTML字符串。您可以使用Option构造函数来创建新的选项元素。

&#13;
&#13;
var locations = [{"name":"Hotel1","address":"Bondi Beach","lat":"6.369869","lng":"80.042055","thumb_path":"img\/hotel1.jpg"},{"name":"Hotel2","address":"Coogee Beach","lat":"6.025822","lng":"80.305727","thumb_path":"img\/hotel2.jpg"},{"name":"Hotel3","address":"Cronulla Beach","lat":"6.691994","lng":"79.928771","thumb_path":"img\/hotel3.jpg"},{"name":"Hotel4","address":"Manly Beach","lat":"6.887130","lng":"80.093420","thumb_path":"img\/hotel4.jpg"},{"name":"Hotel5","address":"Maroubra Beach","lat":"7.362609","lng":"79.825005","thumb_path":"img\/hotel5.jpg"}]

var select = $('#start')[0];
locations.forEach(function(location) {
    select.add(new Option(location.name, location.name));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="start"></select>
&#13;
&#13;
&#13;