[英]How to dynamically build an option list
I have a dropdown list I need to populate with jquery as the list contents will change. 我有一个下拉列表,我需要用jquery填充,因为列表内容将更改。 I found the basis for the following code on this site. 我在此站点上找到了以下代码的基础。 But it is coded to run a set number of items. 但是它被编码为运行一定数量的项目。 Here is my jsfiddle . 这是我的jsfiddle 。 You can see if the button is clicked the list contents change. 您可以查看是否单击了按钮,列表内容发生了变化。 But the list is read from a database and might have 1 item or a hundred. 但是该列表是从数据库中读取的,可能有1项或100项。 So I added a loop to read through the list and add it to the options list but no matter what I tried it failed. 因此,我添加了一个循环以通读列表并将其添加到选项列表,但是无论我尝试了什么失败。 My last attempt is here . 我最后的尝试是在这里 。
My question is how to change from this: 我的问题是如何从此更改:
var options = [
{text: cars[0], value: 1},
{text: cars[1], value: 2},
{text: cars[2], value: 3}
];
to something like this: 像这样:
var options '';
for (var i = 0; i < cars.length; ++i) {
options =
{text: cars[i], value: i},
;
}
options = [ + options + ];
Here is the code from my first jsfiddle: 这是我第一个jsfiddle中的代码:
<script>
var getlist = function() {
var cars = ["Saab", "Volvo", "BMW"];
var options '';
for (var i = 0; i < cars.length; ++i) {
options =
{text: cars[i], value: i},
;
}
options = [ + options + ];
$("#v_make").replaceOptions(options);
}
$('#button').click(getlist);
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window)
</script>
<select id="v_make">
<option>start</option>
</select>
<input type="button" id="button" value="Click Me" />
You could simplify the building of the options by passing the cars
array to your function: 您可以通过将cars
数组传递给函数来简化选项的构建:
var getlist = function() {
var cars = ["Saab", "Volvo", "BMW"];
$("#v_make").replaceOptions(cars);
}
$('#button').click(getlist);
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", index)
.text(option);
self.append($option);
});
};
})(jQuery, window)
Try as follows 尝试如下
$(document).ready(function() { var x = 0; var y = 0; $('#addBtn').on('click', function() { $('<option>').val(x).text(y).appendTo('#select1'); x++ y++ }); })
<select id="select1" style="width:100%;"> <option value="0" selected>(Please select an option)</option> </select> <button id="addBtn">Add</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.