DIV CSS 佈局教程網

用 jQuery 操作 select 下拉列表框的常用代碼
編輯:JQuery特效代碼     

先給出一段示例 HTML:

<select id="sltList" name="list">
<option value="1">張三</option>
<option value="2">李四</option>
</select>

獲取當前選中項的值與文本:

// 獲取當前選中的 option 值
$('#sltList').val()
// 獲取當前選中項的文本
$('#sltList option[@selected]').text();
// 或
var item = $("select[@name= list] option[@selected]").text();

設置與選中操作:

// 設置文本為當前選中項
$("#sltList option[@selected]").attr("text",'張三');
// 設置 select 的第二個元素為當前選中值
$('#sltList')[0].selectedIndex = 1;
// 設置 value=1 的項目為當前選中項
$("#sltList").attr("value",'1');
$('#sltList').val('1');

添加與清空 option:

// 添加下拉框的 option
$("<option value='3'>王五</option><option value='4'>趙六</option>").appendTo("#sltList")
// 清空下拉框
$("sltList").empty();

監聽改變事件:

$("#testSelect").change(function(){
  jQuery('option:selected', this).each(function(){
    alert(this.value);
  });
});

最後補充 append 與 html 的區別:append 是在該元素內容末尾追加 htmlStr,而 html 則是把該元素的內容整體替換為 htmlStr。

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