1. 取得option的值
// get選取option的文字
$('#select').find(':selected').text();
// get選取option的值
$('#select').find(':selected').val();
// 用迴圈取得所有被選取的option
$('#select').find(':selected').each(function() {
alert(this.text); // 文字
alert(this.value); // 值
});
2. 新增option
$('#select').append( $('').attr('value', "值").text('文字') );
3. 刪除option
// 移除選擇的option
$('#select').find(':selected').remove();
// 移除全部的option
$('#select option').remove();
4. 移除選擇的option後,防止卷軸移至最上方
// 先取得要移除項目的 index
var selectIndex = $('#select').find(':selected').index();
// 移除選擇的項目
$('#select').find(':selected').remove();
// 判斷移除項目後,原先的index是否還有option,有的話就直接將此option設定為選取狀態
// 捲軸就不會往上跑了
if ($('#select option').get(selectIndex) != null) {
$('#select option').get(selectIndex).selected = true;
}
else {
// 沒有項目的話,判斷select理是否還有option
// 有的話,表示移除的項目為最後一個,就設定上一個option為選取狀態
if ($('#select option').length > 0) {
$('#select option').get(selectIndex - 1).selected = true;
}
}