我有以下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)未$選擇對象追加到#selectID的第n個孩子,這將是一個OPTGROUP。謝謝你的幫助!
發佈整個腳本或小提琴。 –
爲什麼你會期望'.eq(n)'添加到孩子? '.eq(n)'選擇匹配選擇器的'nnth'元素。 – Barmar
如果你想要第n個孩子,使用'.children()。eq(n)'。 – Barmar