如何使用jquery在下拉列表中绑定数组值

时间:2014-10-16 07:34:17

标签: jquery

我有这个数组

 var serviceArray= new Array("Living Room","Dining Room","Bedroom(s)","Family Room","Kitchen","Den","Hallway(s)","Ste(s)","Bathroom","Landing(s)");

我想使用jquery ..

在以下select标签的选项中绑定所有这些数组值
    <select class="services_list"></select>

4 个答案:

答案 0 :(得分:1)

迭代你的数组并将选项附加到你的选择元素。

Heres示例:

&#13;
&#13;
var serviceArray = new Array("Living Room", "Dining Room", "Bedroom(s)", "Family Room", "Kitchen", "Den", "Hallway(s)", "Ste(s)", "Bathroom", "Landing(s)");

$(document).ready(function() {
  for (i = 0; i < serviceArray.length; i++) {
    $('.services_list').append('<option>' + serviceArray[i] + '</option>')
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="services_list"></select>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我假设您要创建一个包含数组的选项列表,以便您可以使用.each().appendTo()

var serviceArray= new Array("Living Room","Dining Room","Bedroom(s)","Family Room","Kitchen","Den","Hallway(s)","Ste(s)","Bathroom","Landing(s)");
$(serviceArray).each(function(){
    $('<option>'+this+'</option>').appendTo('.services_list');
});

DEMO

答案 2 :(得分:1)

试试此代码

    var options = '';
    var serviceArray= new Array("Living Room","Dining Room","Bedroom(s)","Family Room","Kitchen","Den","Hallway(s)","Ste(s)","Bathroom","Landing(s)");
    for (var i = 0; i < serviceArray.length; i++) {
        options += '<option value="' + serviceArray[i] + '">' + serviceArray[i] + '</option>';
    }
    $('.services_list').html(options);

答案 3 :(得分:1)

试试这个:

Fiddle

上的演示

HTML:

<select class="services_list"></select>

的JavaScript:

var serviceArray= new Array("Living Room","Dining Room","Bedroom(s)","Family Room","Kitchen","Den","Hallway(s)","Ste(s)","Bathroom","Landing(s)");

for (i = 0; i < serviceArray.length; i++) {
    var data = '<option>' + serviceArray[i] + '</option>'
    $('select').append(data);
}