使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
当前回答
选项1-
你可以试试这个-
$('#selectID').append($('<option>',
{
value: value_variable,
text : text_variable
}));
像这样-
对于(i=0;i<10;i++){ $('#mySelect').append($('<option>',{值:i,text:“选项”+i}));}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><select id='mySelect'></select>
选项2-
或者试试这个-
$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );
像这样-
对于(i=0;i<10;i++){ $('#mySelect').append('<option value=“'+i+'”>'+'option'+i+'</option>');}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><select id='mySelect'></select>
其他回答
为什么不简单呢?
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')
此处测试:
for(设i=0;i<10;i++){$('<option/>').val(i).text('option'+i).appendTo('#mySelect')}<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><select id=“mySelect”></select>
无论出于何种原因执行$(“#myselect”).append(新选项(“text”,“text”));在IE7中对我不起作用+
我必须使用$(“#myselect”).html(“<option value='text'>text</option>”);
仅通过单线
$.each(result, function (k,v) {
**if(k == selectedMonthNumber) var selectedMonth = 'selected'; else var selectedMonth = '';**
$("#periodMonth").append($('<option>', {
value: k,
text: v,
**selected: selectedMonth**
}));
})
如果有人来这里寻找添加数据财产选项的方法
使用属性
var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);
使用数据-版本1.2.3
var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);
如果选项名称或值是动态的,则不必担心其中的特殊字符会被转义;在这种情况下,您可能更喜欢简单的DOM方法:
var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');