简体   繁体   English

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

[英]How to bind array values in dropdown using jquery

I am having this array 我有这个数组

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

I want to bind all this array values in option of following select tag using jquery.. 我想在所有使用jQuery的选择标记的选项中绑定所有这些数组值。

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

Iterate your array and append option to your select element. 迭代数组,并将选项追加到select元素。

Heres Example: 继承人示例:

 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>') } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="services_list"></select> 

I'm assuming you want to create a select option list with the array so you can use .each() and .appendTo() 我假设您想使用数组创建选择选项列表,以便可以使用.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 DEMO

Try this code 试试这个代码

    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);

Try this: 尝试这个:

Demo on Fiddle 小提琴演示

HTML: HTML:

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

JavaScript: 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM