[英]Create select field dynamically - >selected< option doesn't show up
[英]How to dynamically create select with selected option
我正在像这样动态select tag
,我想third option selected
var dropDownList = $('<select />', {
'id': 'my id', // some id i want to apply
'class': 'my class', //some class i want to aply
});
for (iLoop = 0; iLoop < myarray.length ; ++iLoop) {
if(iLoop ==2){
$('<option />', {
'value': myarray[iLoop ].value,
'text': myarray[iLoop ].text,
'selected': ?? // true/false
}).appendTo(dropDownList);
}
else{
$('<option />', {
'value': myarray[iLoop ].value,
'text': myarray[iLoop ].text,
}).appendTo(dropDownList);
}
}
旁边我不想这样
var selectElement='<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel" selected>Opel</option>
<option value="audi">Audi</option>
</select>';
for (iLoop = 0; iLoop < myarray.length ; ++iLoop)
如果您正在编写for循环,请不要计算循环内部的数组长度。 最好如下使用
var myarrayLength = myarray.length;
for (iLoop = 0; iLoop < myarrayLength ; ++iLoop)
不要像下面这样比较。 如果数组大小为n,则此比较将发生n次
'selected': (iLoop == 2 ? true : false)
最好使用for循环而不是for循环。
for (iLoop in myarray) {
$('<option />', { 'value': myarray[iLoop ].value,
'text': myarray[iLoop ].text,
}).appendTo(dropDownList);
}
$("#time_entry_activity_id option:eq(3)").attr('selected', 'selected');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.