我正在尝试使用jQuery填充数组的下拉选择.
这是我的代码:
// Add the list of numbers to the drop down here
var numbers[] = { 1, 2, 3, 4, 5};
$.each(numbers, function(val, text) {
$('#items').append(
$('<option></option>').val(val).html(text)
);
// END
Run Code Online (Sandbox Code Playgroud)
但是我收到了一个错误.每个功能都是我离开这个网站的东西.
是否因为我正在使用一维数组而轰炸?我希望选项和文本都一样.
Rei*_*gel 93
尝试循环:
var numbers = [1, 2, 3, 4, 5];
for (var i=0;i<numbers.length;i++){
$('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}
Run Code Online (Sandbox Code Playgroud)
更好的方法:
var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);
Run Code Online (Sandbox Code Playgroud)
Fab*_*ani 39
数组声明的语法不正确.请尝试以下方法:
var numbers = [ 1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
循环部分似乎正确
$.each(numbers, function(val, text) {
$('#items').append( $('<option></option>').val(val).html(text) )
}); // there was also a ) missing here
Run Code Online (Sandbox Code Playgroud)
正如@Reigel所做的似乎增加了更多的性能(在这样的小阵列上并不明显)
你也可以这样做:
var list = $('#items')[0]; // HTMLSelectElement
$.each(numbers, function(index, text) {
list.options[list.options.length] = new Option(index, text);
});
Run Code Online (Sandbox Code Playgroud)