標籤:io 使用 ar c on cti html r new
T1 >>> 建立一個新的select
var $newSelect = $("<select id=\"sel\" name=\"s_name\"></select>"); // 注意轉義\
T2 >>> 建立一個新的option
var $option = $("<option value=\"value\">1</option>");
T3 >>> 將option添加進數組 options
方式一:
$newSelect.append($option);
方式二:
$newSelect.append("<option value=\"value\">1</option>"); // 添加到 option 序列最後
方式三:
$newSelect.prepend("<option value=\"value\">1</option>"); // 添加到 option 序列最前
// 不支援option索引值溢出添加新的option
T4 >>> 將select添加到頁面
$newSelect.appendTo(‘body‘);
$newSelect.appendTo($(‘body‘));
$(‘body‘).append($newSelect);
// append() 和 appendTo() 方法執行的任務相同。
// 不同之處在於:內容和選取器的位置,以及 append() 能夠使用函數來附加內容。
$(selector).append(function(index,html))
T5 >>> 清除select的option選項
$("#sel option[value=‘1‘]").remove(); // 移除 value 值為 1 的 option
$("#sel option[index=2]").remove(); // 移除索引為 2 的 option
$("#sel option[text=‘_txt‘]").remove(); // 移除 text 值為 _txt 的 option
$("#sel option:last").remove(); // 移除最後的 option
$("#sel option:selected").remove(); // 移除selected選中的 option
T6 >>> 修改select的option選項
// 選中項的 text 值
newSelect.find(‘option:selected‘).text();
// 選中項的Value值
$newSelect.val()
$newSelect.find(‘option:selected‘).val();
$(‘select[name="s_name"]‘).find(‘option:selected‘).val();
// 任意項的 text val 值
$newSelect.find(‘option‘).eq(index).text();
$newSelect.find(‘option‘).eq(index).val();
$newSelect.children(‘option‘).eq(index).text();
$newSelect.children(‘option‘).eq(index).val();
$("#sel option[value=‘1‘]").text();
$("#sel option[value=‘1‘]").val();
$("#sel option[index=2]").text();
$("#sel option[index=2]").val();
$("#sel option[text=‘_txt‘]").text();
$("#sel option[text=‘_txt‘]").val();
// 輸出 option 序列的所有 text 值。
$newSelect.text()
// 輸出 select 被選中的索引值 。
$("#sel").get(0).selectedIndex; // get(0) 將jquery對象轉化為DOM形式。
$("#sel option:selected").index()
// 擷取 option 的長度值
$("#sel option").length
$newSelect.find(‘option‘).length
$newSelect.children(‘option‘).length
>>> 整個流程
<script>
var $newSelect = $("<select id=\"sel\"></select>");
var $option = $("<option value=\"1\">1</option>");
$(‘body‘).append($newSelect);
$newSelect.append($option);
</script>
註:有時候用到的jquery和Dom元素的一些轉換方式:
$(this)[0]
$(this).get(0)
$(this).toArray()[0];
以上3種寫法等價
jquery操作select的一些基本方法總結