我不明白为什么要注释的代码可以将选项附加到选择标签上,但是当我尝试创建数组并使用for for loop来添加所有值时数组作为选项,代码不起作用。如果我缺少简单的东西,我深表歉意。预先感谢您。
//var testing ="testing value"
//$('#test').append('<option>'+testing+'</option>');
var testArray = ['test1', 'test2', 'test3'];
for(var i=0, i < testArray.length, i++) {
var value = testArray[i];
$('#test').append('<option>'+value+'</option>');
}
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<select id="test">
<option>--</option>
</select>
问题是。定义循环的变量侧面并附加标记。
var testArray = ['test1', 'test2', 'test3'];
var html = '';
for (var i = 0; i < testArray.length; i++) {
var value = testArray[i];
html += '<option>' + value + '</option>';
}
$('#test').append(html);
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<select id="test">
<option>--</option>
</select>
尝试此
$.each(testArray, function(key, value) {
$('#test')
.append($('<option>', { value : key })
.text(value));
});