我有以下 html 结构,并试图通过 javascript 在 optgroups 中添加选项元素。我也在使用 jquery 移动框架。
HTML如下:
<form>
<div class="ui-field-contain">
<label for="selectID">Look-up</label>
<select name="select-native-4" id="selectID">
<option>Choose...</option>
<optgroup label="G1" id="group1">
</optgroup>
<optgroup label="G2" id="group2">
</optgroup>
<optgroup label="G3" id="group3">
</optgroup>
</select>
</div>
</form>
javascript如下。
for( var i = 0; i < array.length; i++){
var item = array[i];
var $option = $('<option> ' + item.name + ' </option>');
$option.prop('value', item.memb);
console.log(item.name);
var tp = -1;
switch(item.name){
case 'group1' :
tp = 1; break;
case 'group2' :
tp = 2; break;
case 'group3' :
tp = 3; break;
}
console.log(tp);
//$("#selectID :nth-child(tp)").append($option);
$("#selectID").eq(tp).append($option);
}
$('#selectID').selectmenu('refresh');
}
我很困惑为什么 .eq(n) 不将 $option 对象附加到 #selectID 的第 n 个子对象,这将是一个 optgroup。感谢您的帮助!
最佳答案
您只有 1 个#selectID。你需要:
$('#selectID optgroup').eq(tp).append($option);
这将命中您选择的 id 中的 optgroups。
关于javascript - 动态添加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24166411/