DIV CSS 佈局教程網

jQuery 操作下拉選單 DropDownList 取值與賦值大全
編輯:JQuery特效代碼     

下拉選單(DropDownList / select)是表單中不可或缺的元素。jQuery 提供了豐富的方法來操作它的取值、賦值、增刪與遍歷。以下整理最常見的 16 種操作寫法,方便日後查閱。

1. 取得選中項

//獲取選中項的 Value 值:
$('select#sel option:selected').val();
//或者
$('select#sel').find('option:selected').val();

//獲取選中項的 Text 值:
$('select#sel option:selected').text();
//或者
$('select#sel').find('option:selected').text();

2. 取得當前選中項的索引值

$('select#sel').get(0).selectedIndex;

3. 取得當前 option 的最大索引值

$('select#sel option:last').attr("index")

4. 取得 DropdownList 的長度

$('select#sel')[0].options.length;
//或者
$('select#sel').get(0).options.length;

5. 設置第一個 option 為選中值

$('select#sel option:first').attr('selected','true')
//或者
$('select#sel')[0].selectedIndex = 0;

6. 設置最後一個 option 為選中值

$('select#sel option:last).attr('selected','true')

7. 根據索引值設置任意 option 為選中值

$('select#sel')[0].selectedIndex =索引值;//索引值=0,1,2....

8. 設置 Value=4 的 option 為選中值

$('select#sel').attr('value','4');
//或者
$("select#sel option[value='4']").attr('selected', 'true');

9. 刪除 Value=3 的 option

$("select#sel option[value='3']").remove();

10. 刪除第幾個 option

$(" select#sel option ").eq(索引值).remove();//索引值=0,1,2....
//如刪除第 3 個:
$(" select#sel option ").eq(2).remove();

11. 刪除第一個 option

$(" select#sel option ").eq(0).remove();
//或者
$("select#sel option:first").remove();

12. 刪除最後一個 option

$("select#sel option:last").remove();

13. 刪除整個 dropdownlist

$("select#sel").remove();

14. 在 select 後面添加一個 option

$("select#sel").append("<option>f</option>");

15. 在 select 前面添加一個 option

$("select#sel").prepend("<option>0</option>");

16. 遍歷 option

$(' select#sel option ').each(function (index, domEle) {
//寫入代碼
});

把這份清單收藏起來,日常處理下拉選單時幾乎所有情境都能對應到其中一種寫法。核心觀念是:取值多用 :selected 選擇器搭配 val()/text(),增刪則善用 append、prepend、remove 與 eq(),遍歷時用 each() 即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved